模拟 HttpClient.SendAsync 到 return 响应,内容不为空

Mock HttpClient.SendAsync to return response with Content not null

我正在尝试模拟 var response = await httpClient.SendAsync(request, CancellationToken.None);,但我的 response.Content 始终是 null

我的模拟看起来像...

var httpResponseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
httpResponseMessage.Content = new StringContent("test content", System.Text.Encoding.UTF8, "application/json");
A.CallTo(() => httpClient.SendAsync(A.Fake<HttpRequestMessage>(), CancellationToken.None)).Returns(Task.FromResult(httpResponseMessage));

它似乎被正确模拟了,但 response.Content 为空,但状态代码 - 例如 - 反映了我在测试中设置的内容。

我相信你们中的某个人遇到过这个问题,我们将不胜感激。谢谢。

可能没有匹配到对 SendAsync 的调用。我看到你配置了你的假货来回应

A.CallTo(() => httpClient.SendAsync(A.Fake<HttpRequestMessage>(), CancellationToken.None))

但是您的生产代码不太可能传递第一个参数,该参数比较等于您在此处的 A.Fake<HttpRequestMessage>() 参数。

你的意思是

A.CallTo(() => httpClient.SendAsync(A<HttpRequestMessage>.Ignored, CancellationToken.None))

(或等同于 A<HttpRequestMessage>._)?

您可以在 Argument constraints page. Specifically, see how to match any argument at the Ignoring arguments 子主题上阅读有关如何匹配参数的信息。