RestSharp单元测试NUnit Moq RestResponse空引用异常 [英] RestSharp Unit Test NUnit Moq RestResponse null reference exception

查看:83
本文介绍了RestSharp单元测试NUnit Moq RestResponse空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将Moq与RestSharp结合使用时,我遇到了一些挑战.也许这是我对Moq的误解,但由于某些原因,在尝试模拟RestResponse时,我不断收到null引用异常.

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.

这是我的单元测试.

    [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;
    }
}

由于某种原因,响应对象为null.可能是我在错误地模拟返回对象吗?

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

推荐答案

出于公开目的,我假设您的IncidentRestClient具有一个构造函数,该构造函数将 IRestClient 实例用作参数,并使用它来设置 client 成员.

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.

在您的测试中,您似乎正在运行安装程序,以使Execute的重载不同于您正在使用的重载.代替:

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(

尝试:

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

这篇关于RestSharp单元测试NUnit Moq RestResponse空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆