c# - 如何检查参数是否具有某些属性值?
问题描述
我正在尝试对 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
方法,而是有一个扩展方法。
解决方案
问题在于 ... 的Get
功能,IRestClient
因为它没有。这只是RestClientExtensions
. 正如您在源代码中看到的那样,它只是Execute
使用Method.GET
as 参数调用。所以正确的存根方法
clientStub
.Get(
Arg.Any<RestSharp.IRestRequest>()
)
.Returns(responseStub);
是这样做的:
clientStub
.Execute(
Arg.Any<RestSharp.IRestRequest>(),
Method.GET
)
.Returns(responseStub);
推荐阅读
- firebase - Flutter - 提交表单时如何将DropDownMenu的选定索引保存到FireStore
- c# - 为什么 Visual Studio 2013 中没有安装实体框架包?
- gmail-api - 服务“gmail.googleapis.com”的配额指标“查询”和限制“每个用户每分钟的查询数”超出配额
- ios - iOS 权限描述限制
- powershell - 将 PSCustomObject 添加到数组会产生错误,但在 Powershell 中调试代码时工作正常
- reactjs - 当我通过真实性测试时,ReactJS 给了我无法访问的代码
- c++ - 关于:C++ 中异常对象的范围:为什么我没有得到副本?
- python - eq函数python的对面/选择列中具有两个以上相同条目的行
- date - 如何将包含月份和年份的日文日期拆分为日期格式
- html - 如果用户一直按下按钮(查看更多),多次没有结果