【问题标题】:Net Core testing method with HttpClient使用 HttpClient 的 Net Core 测试方法
【发布时间】: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).'

我做错了什么?

【问题讨论】:

标签: c# asp.net-core httpclient moq


【解决方案1】:

处理程序上没有PostAsync 方法。

你需要模拟SendAsync(HttpRequestMessage, CancellationToken)

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多