首页 > 解决方案 > 如何检查参数是否具有某些属性值?

问题描述

我正在尝试对 RestClient 进行存根以返回特定请求的特定响应,该响应通过检查使用的 URL 的结尾来识别。这是我想出的代码:

_clientStub = Substitute.For<IRestClient>();
_responseStub = Substitute.For<IRestResponse>();
_clientStub
    .Get(
        Arg.Is<IRestRequest>(
            request => request.Resource.EndsWith("config.json")
        )
    )
    .Returns(_responseStub);

我收到一个NullReferenceException零件Arg.Is<IRestRequest>,如果我尝试将它保存在一个变量中以便像这样重用,该变量的计算结果为null

protected static readonly IRestRequest CONFIG_QUERY =
    Arg.Is<IRestRequest>(
        request => request.Resource.EndsWith("config.json")
    );

我正在关注文档中的第二个示例,所以我不确定出了什么问题。有什么帮助吗?


澄清

为了重现性,我创建了一个最小的示例:

[Fact]
public void StackOverflowTest()
{
    RestSharp.IRestClient clientStub = Substitute.For<RestSharp.IRestClient>();
    RestSharp.IRestResponse responseStub = Substitute.For<RestSharp.IRestResponse>();
    clientStub
        .Get(
            Arg.Any<RestSharp.IRestRequest>()
        )
        .Returns(responseStub);
}

是的,此测试中没有断言。因为最后一个命令已经抛出 and ,所以我什至都没有找到它们NullReferenceException。接口来自RestSharp,但这并不重要。


更新

为了缩小问题范围,我创建了一个更简单的示例,现在它可以工作了:

public interface IStackOverflowResponse { };
public interface IStackOverflowRequest { };
public interface IStackOverflowClient
{
    IStackOverflowResponse Get(IStackOverflowRequest request);
}

[Fact]
public void StackOverflowTest()
{
    IStackOverflowClient clientStub = Substitute.For<IStackOverflowClient>();
    IStackOverflowResponse responseStub = Substitute.For<IStackOverflowResponse>();
    clientStub
        .Get(
            Arg.Any<IStackOverflowRequest>()
        )
        .Returns(responseStub);
}

所以现在我猜想 mocking 有一个特定的问题RestSharp.RestClient。我想问题在于模拟/存根扩展方法,因为 IRestClient 本身没有Get方法,而是有一个扩展方法。

标签: c#restsharpnsubstitute

解决方案


问题在于 ... 的Get功能,IRestClient因为它没有。这只是RestClientExtensions. 正如您在源代码中看到的那样,它只是Execute使用Method.GETas 参数调用。所以正确的存根方法

clientStub
    .Get(
        Arg.Any<RestSharp.IRestRequest>()
    )
    .Returns(responseStub);

是这样做的:

clientStub
    .Execute(
        Arg.Any<RestSharp.IRestRequest>(),
        Method.GET
    )
    .Returns(responseStub);


推荐阅读