![](/img/trans.png)
[英]How to stub a method by matching an argument by a superclass in NSubstitute?
[英]Argument matching not working properly with 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
如果有人想要重現這個,那么這是StringResponse
方法:
private HttpResponseMessage StringResponse(string content)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (content != null)
{
response.Content = new StringContent(content);
}
return response;
}
我究竟做錯了什么?
它適用於我
httpClient.PostAsync("/login", Arg.Any<StringContent>())
.ReturnsForAnyArgs(this.StringResponse("{\"token\": \"token_content\"}"));
但是我不需要任何參數,我需要其中一個是字符串"/login"
而另一個是StringContent
類型。
我試圖在Arg.Is
調用中添加一些更通用的東西,如HttpContent
但這也不起作用。
我在.NET Core上使用NSubstitute 2.0.0-rc
,但我也嘗試在標准控制台應用程序上使用NSubstitute 1.10.0
並獲得相同的結果。
這里的問題是public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
方法不是虛擬的,並且NSubstitute無法正確鏈接您的參數規范和返回值到方法。 這是基於Castle.Core
的所有Castle.Core
庫的問題。
重要的是,NSubstitute將規范鏈接到執行堆棧中的第一個虛擬方法,結果是堆棧中某處的public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
方法。 你很“幸運”擁有相同的返回類型。 正如你所看到的那樣,它有不同的論點,顯然與你提供的論點不符。 令人驚訝的是, ReturnsForAnyArgs()
可以工作,因為它不會檢查您提供的參數規范。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.