Net Core 测试方法与 HttpClient

Net Core testing method with HttpClient

我有一个使用 HttpClient 执行请求的服务方法。服务 class 构造函数注入 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).'

我做错了什么?

处理程序上没有 PostAsync 方法。

你需要模拟 SendAsync(HttpRequestMessage, CancellationToken)