【问题标题】:RestSharp Unit Test NUnit Moq RestResponse null reference exceptionRestSharp 单元测试 NUnit Moq RestResponse 空引用异常
【发布时间】:2015-05-12 00:24:01
【问题描述】:

我在尝试将 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());
    }

这是我的实际实现:

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

由于某种原因,响应对象为空。会不会是我错误地模拟了返回对象?

【问题讨论】:

  • 什么是“IncidentRestClient”?是你定义的类型吗?
  • 嗨,肖恩。是的,这是我定义的类型。请参阅上面的编辑。
  • 看起来你的IncidentRestClient 的构造函数没有将IRestClient 作为参数。是否定义了另一个接受该参数的构造函数?

标签: c# moq restsharp


【解决方案1】:

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

看起来,在您的测试中,您正在运行安装程序的 Execute 重载与您正在使用的重载不同。而不是:

.Setup(x => x.Execute(

尝试:

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

【讨论】:

  • 嗨,肖恩。太感谢了!! :) 我不敢相信我在设置中忽略了这个重载。我现在得到了一个 RestReponse 对象。
  • 是的,它有constructor public IncidentRestClient(IRestClient client) { this.client = client; }
  • @jaypman 如果它是正确/有用的,您应该接受这个答案。一个upvote会很好。这就是它的工作原理。
  • @ToddMenier 我现在无法投票,因为它说我需要至少 15 个声望点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多