C
C#9mo 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;
}
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.
System.InvalidOperationException: Handler did not return a response message.
4 Replies
dan in a can
dan in a can9mo ago
does it work if you change your SetupRequest to SetupAnyRequest? I know you probably don't want it that way ultimately, just trying to narrow it down
Spaxter
Spaxter9mo ago
Yeah, it does
dan in a can
dan in a can9mo ago
so you're missing something in your request matching or rather, have something wrong I haven't used that library before, always just used the out of the box Setup are you sure the verb + url are correct?
Spaxter
Spaxter9mo ago
Yeah, I've tried debugging and they all look correct. The code itself works, it's just that all tests fail because of this exception being thrown Turns out it had something to do with the way BaseAddress was being parsed, managed to fix it by changing the way I add endpoints to the request URI