seb*_*ibu 1 c# moq httpclient asp.net-core
我有一个使用 执行请求的服务方法HttpClient。服务类构造函数IHttpClientFactory使用以下代码注入并创建客户端:
_httpClient = httpClientFactory.CreateClient(url);
Run Code Online (Sandbox Code Playgroud)
在我的测试构造函数中,我试图模拟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);
}
Run Code Online (Sandbox Code Playgroud)
设置mockHttpMessageHandler 时出现以下错误:System.ArgumentException: 'No protected method HttpMessageHandler.PostAsync found whose signature is compatible with the provided arguments (string, HttpContent).'
我究竟做错了什么?