RestSharp Unit Test NUnit Moq RestResponse null reference

I am having some problems trying to use Moq with RestSharp. This may be a misunderstanding of mine regarding Moq, but for some reason I keep getting a null reference exception when trying to debug 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 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;
    }
}

      

The response object is null for some reason. Maybe I am mocking the returned object incorrectly?

+3


source to share


1 answer


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

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

.Setup(x => x.Execute(

      



try:

.Setup(x => x.Execute<RootObjectList>(

      

+9


source







All Articles