Overview
Since HttpClient
is not backed by an interface, the approach to get an HttpClient
for testing is different:
- Mock
HttpMessageHandler
:var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
- Set up the mock:
// Call Protected() since since HttpMessageHandler's constructor is protected: handlerMock.Protected() // Override HttpMessageHandler's protected internal abstract SendAsync method: .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(httpGetResponseStringContent) });
- Pass the mocked
HttpMessageHandler
to theHttpClient
constructor to get a testHttpClient
:var httpClient = new HttpClient(handlerMock.Object);
- Pass that
HttpClient
to the system under test that would normally receive an injectedHttpClient
instance:var sut = new SomeService(httpclient, ...);