C#C
C#3y ago
Spaxter

✅ Unit Testing HttpClient

Hello, I'm currently trying to write some unit tests for a class that uses an HttpClientFactory through DI. This is the just of what I'm doing in these tests:
private string myApiUrl = "https://www.some-api.com";
private IHttpClientFactory _httpClientFactory;
private Mock<HttpMessageHandler> _httpClientMock;

[SetUp]
public void SetUp()
{
  _httpClientMock = new Mock<HttpMessageHandler>();
  _httpClientMock.SetupRequest(HttpMethod.Post, $"{myApiUrl}/example").ReturnsResponse("Example response");

  var httpClientFactoryMock = new Mock<IHttpClientFactory>();
  httpClientFactoryMock.Setup(c => c.CreateClient("exampleApi")).Returns(new HttpClient(_httpClientMock.Object)
  {
      BaseAddress = new Uri(myApiUrl)
  });
  
  _httpClientFactory = httpClientFactoryMock.Object;
}


But every test that uses the IHttpClientFactory throws the following exception:
System.InvalidOperationException: Handler did not return a response message.
Was this page helpful?