【发布时间】:2021-04-10 15:37:19
【问题描述】:
我有一个使用HttpClient 执行请求的服务方法。服务类构造函数注入IHttpClientFactory 并使用以下代码创建客户端:
_httpClient = httpClientFactory.CreateClient(url);
在我的测试构造函数中,我试图模拟 PostAsync 方法响应。
public MyServiceUnitTests()
{
_HttpClientMock = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("PostAsync", ItExpr.IsAny<string>(), ItExpr.IsAny<HttpContent>())
.ReturnsAsync(new HttpResponseMessage{ StatusCode = HttpStatusCode.OK });
var httpClient = new HttpClient(mockHttpMessageHandler.Object);
_HttpClientMock.Setup(x => x.CreateClient(It.IsAny<string>())).Returns(httpClient);
_Service = new MyService(_HttpClientMock.Object);
}
设置 mockHttpMessageHandler 时出现以下错误:System.ArgumentException: 'No protected method HttpMessageHandler.PostAsync found whose signature is compatible with the provided arguments (string, HttpContent).'
我做错了什么?
【问题讨论】:
-
您可以在评分答案stackoverflow.com/questions/36425008/…中查看类似的实现
-
请同时查看this article
标签: c# asp.net-core httpclient moq