7

I'm having some challenges trying to use Moq with RestSharp. Maybe it's it my misunderstanding of Moq but for some reason I keep on getting a null reference exception when trying to Mock a RestResponse.

Here is my unit test.

    [Test]
    public void GetAll_Method_Throws_exception_if_response_Data_is_Null()
    {
        var restClient = new Mock<IRestClient>();

        restClient.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
            .Returns(new RestResponse<RootObjectList>
            {
                StatusCode = HttpStatusCode.OK,
                Content = null
            } );

        var client = new IncidentRestClient(restClient.Object);

        Assert.Throws<Exception>(() => client.GetAll());
    }

Here is my actually implementation:

public class IncidentRestClient : IIncidentRestClient
{
    private readonly IRestClient client;
    private readonly string url = "some url here";

    public IncidentRestClient()
    {
        client = new RestClient { BaseUrl = new Uri(url) };
    }

    public RootObjectList  GetAll()
    {
        var request = new RestRequest("api/now/table/incident", Method.GET) { RequestFormat = DataFormat.Json };
        request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

        IRestResponse<RootObjectList> response = client.Execute<RootObjectList>(request);

        if (response.Data == null)
            throw new Exception(response.ErrorException.ToString());

        return response.Data;
    }
}

For some reason response object is null. Could it be I'm mocking the return object incorrectly?

jaypman
  • 167
  • 2
  • 11

1 Answers1

13

For disclosure purposes, I am assuming that your IncidentRestClient has a constructor that takes an IRestClient instance as a parameter and uses it to set the client member.

It looks like, in your test, you are running Setup for a different overload of Execute than the one you are using. Instead of:

.Setup(x => x.Execute(

try:

.Setup(x => x.Execute<RootObjectList>(
Sean H
  • 736
  • 6
  • 9
  • Hi Sean. Thank you so much!! :) I can't believe I overlooked this overload in the Setup. I now get a RestReponse object back. – jaypman May 11 '15 at 20:05
  • Yes, it has contructor public IncidentRestClient(IRestClient client) { this.client = client; } – jaypman May 11 '15 at 20:14
  • 2
    @jaypman You should accept this answer if it was correct/helpful. An upvote would be nice to. That's how this works. – Todd Menier May 16 '15 at 14:36
  • @ToddMenier I cannot upvote at the moment b/c it says I need at least 15 reputation points. – jaypman May 27 '15 at 13:06