I've read some documentation on how to mock or emulate the HttpClient, but I cannot reproduce successfully for my unit tests. As of now I cannot interface HttpClient, so I opted for the injection of the HttpMessageHandler, and the idea is to setup it in order to return my response to any call made to the client.
Here is the code to be tested :
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
}
}
}
}
Here is the code in the Test
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);
The observed behavior is no response is made from the client, and I'm stuck at the using(var response...) line.
Where did I go wrong ? I've tried to follow closely this tutorial but it appears I've missed something. https://gingter.org/2018/07/26/how-to-mock-httpclient-in-your-net-c-unit-tests/
Thanks for your help !