RestSharp单元测试NUnit Moq RestResponse空引用异常

jay*_*man 5 c# moq restsharp

我在尝试使用Moq和RestSharp时遇到了一些挑战.也许这是我对Moq的误解,但由于某种原因,我在尝试模拟RestResponse时继续获得空引用异常.

这是我的单元测试.

    [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());
    }
Run Code Online (Sandbox Code Playgroud)

这是我的实际实现:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,响应对象为空.可能是我在错误地嘲笑返回物体吗?

小智 10

出于泄露目的,我假设您的IncidentRestClient具有一个构造函数,该构造函数将IRestClient实例作为参数并使用它来设置客户端成员.

看起来,在您的测试中,您正在运行安装程序,以执行与您正在使用的Execute不同的Execute重载.代替:

.Setup(x => x.Execute(
Run Code Online (Sandbox Code Playgroud)

尝试:

.Setup(x => x.Execute<RootObjectList>(
Run Code Online (Sandbox Code Playgroud)

  • @jaypman你应该接受这个答案,如果它是正确/有帮助的.一个upvote会很好.这是如何工作的. (2认同)