使用HttpClient.GetAsync()的UTest

时间:2018-11-20 10:14:16

标签: c# unit-testing dotnet-httpclient

我已经阅读了一些有关如何模拟或模拟HttpClient的文档,但是我无法成功复制单元测试。到目前为止,我无法连接HttpClient,所以我选择注入HttpMessageHandler,其想法是对其进行设置,以便将对任何对客户端的调用的响应返回给我。

这是要测试的代码:

internal async Task Poll(Func<TimeSpan?, HttpClient> httpClientFactory, CancellationToken cancellationToken)
{
    using (var client = httpClientFactory(_requestTimeout))
    {
        try
        {
            using (var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false))
            {
                // Do stuff with that
            }
        }
    }
}

这是测试中的代码

var response = new HttpResponseMessage(httpStatusCode) { Content = responseContent };

var mockHttp = new Mock<HttpMessageHandler>();
mockHttp.Protected()
    .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(response);

var client = new HttpClient(mockHttp.Object);

var mockedClientFactrory = new Mock<Func<TimeSpan?, HttpClient>>();
mockedClientFactrory.Setup(clientFactory => clientFactory(It.IsAny<TimeSpan?>())).Returns(client);

观察到的行为是客户端未做出任何响应,而我陷入了using(var response ...)行。

我哪里出错了?我试图严格按照本教程进行操作,但似乎我错过了一些东西。 https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

无需模拟函数委托。

创建实际功能

//...

Func<TimeSpan?, HttpClient> clientFactrory = _ => client;

//...