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
HttpMessageHandlerto theHttpClientconstructor to get a testHttpClient:var httpClient = new HttpClient(handlerMock.Object); - Pass that
HttpClientto the system under test that would normally receive an injectedHttpClientinstance:var sut = new SomeService(httpclient, ...);