Unit Test and mock HttpClientFactory in .NET Core

Unit Test and Mock Typed HttpClient using HttpClientFactory in NET Core

In this article, we will see how to Unit Test and mock HttpClientFactory in .NET Core.

We will Unit Test and Mock Typed HTTPClient request objects created using HttpClientFactory interfaces with proper moq mocking in .NET Core.

In our last article, we already learned how to mock basic HTTPClient and Named HTTPClient using HTTPClientFactory.

HTTTPClient object can be created using HttpClientFactory in .NET Core as it provides multiple benefits which we discussed in our article on HTTPClient Vs HTTPClientfactory.

HttpClientFacory interface lets you create HTTPClient objects like using Named HTTPClient and Typed HTTPClient.

Today in this article, we will cover below aspects,

Today in this post we will see how to mock only Typed HTTPClient using the HttpClientFactory interface.

One can also mock Named HTTPClient as discussed in the below article.

Below is a sample code API created using ASP.NET Core 3.1 or .NET 6 and demonstrates Typed HTTPClient usage which we shall be unit testing and mocking using XUnit and Moq.

Unit Test and Mock Typed HttpClient using HttpClientFactory in NET Core

Let’s get started,

1. Mock IHttpClientFactory interface

So as a first step we should be mocking IHttpClientFactory and all its extension methods.

Being an interface IHttpClientFactory is very easy to mock as below,

//Arrange var mockFactory = new Mock<IHttpClientFactory>();

2. Mock HTTPClient object

As a next step, We need to create explicit actual HTTPClient mock objects to passed to the extension method of IHttpClientFactory i.e CreateClient().

The best way to create a mock HTTPClient instance is by mocking HttpMessageHandler. Mocking of HttpMessageHandler will also ensure the client calling actual endpoints are faked by intercepting it.

Below is complete code,

var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
            mockHttpMessageHandler.Protected()
                .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent("{'name':thecodebuzz,'city':'USA'}"),
                });
            var client = new HttpClient(mockHttpMessageHandler.Object);
            mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);

So far so good!

3. Setup Typed HTTPClient with the mock object

Setup AccountClient (Typed HTTPClient) with the mock HTTPClient objects.

AccountClient typedHttpClient = new AccountClient(client);

4. Controller with mocked IHttpClientFactory

Let’s initialize Controller with mocked Typed HTTPClient object created above i.e ‘typedHttpClient‘.

Below Constructor DI injection for HttpClient object technique can be applied in any module or class and hence mocking of IHttpClientFactory will follow the same way of mocking

AccountPersonalController controller = new AccountPersonalController(typedHttpClient);

All the above 3 steps to ensure our Arrange configurations for Unit Testing are decent.

Let’s Invoke the method as below,

           //Act
            var result = await controller.OnGet() as ObjectResult;

Assert the Results

Finally, assert the actual result Vs expected.

            //Assert
            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.OK,       (HttpStatusCode)result.StatusCode);

Finally, we are all set with the Test results and Unit test cases pass successfully for the given scenario.

Using MSTest to mock and unit HttpClientFactory

Unit Test and Mock Named HTTPClient

If you have a Basic or Named HTTPClient object, then please see below the article to understand the mocking of the IHttpClientFactory interface.

That’s All, Happy coding !!

If you have any inputs or any better suggestions, please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.