Hri*_*lev 4 .net c# mocking httpclient nsubstitute
我有这个代码,无论如何都无法让httpClient返回字符串响应.
HttpClient httpClient = Substitute.For<HttpClient>();
httpClient.PostAsync("/login", Arg.Any<StringContent>())
.Returns(this.StringResponse("{\"token\": \"token_content\"}"));
Console.WriteLine(await httpClient.PostAsync("/login", new StringContent(string.Empty)) == null); // True
Run Code Online (Sandbox Code Playgroud)
StringResponse如果有人想要重现这个方法,这是方法:
private HttpResponseMessage StringResponse(string content)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (content != null)
{
response.Content = new StringContent(content);
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
它适用于我
httpClient.PostAsync("/login", Arg.Any<StringContent>())
.ReturnsForAnyArgs(this.StringResponse("{\"token\": \"token_content\"}"));
Run Code Online (Sandbox Code Playgroud)
但我不需要任何参数,我需要其中一个作为字符串"/login"而另一个是类型StringContent.
我试图在Arg.Is通话中添加一些更通用的内容,HttpContent但这也不起作用.
我正在使用NSubstitute 2.0.0-rc.NET Core,但我也尝试NSubstitute 1.10.0在标准控制台应用程序上使用并获得相同的结果.
这里的问题是该public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)方法不是虚拟的,并且NSubstitute无法正确地将您的参数规范和返回值链接到该方法.这是基于所有模拟库的问题Castle.Core.
重要的是,NSubstitute将规范链接到执行堆栈中的第一个虚拟方法,后者最终成为public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)堆栈中的某个方法.你很"幸运"拥有相同的返回类型.正如你所看到的那样,它有不同的论点,显然与你提供的论点不符.令人惊讶的是,ReturnsForAnyArgs()因为它不会检查您提供的参数规范.
| 归档时间: |
|
| 查看次数: |
500 次 |
| 最近记录: |