Unit Testing

Mock http request in C# for Unit testing

A short guide to mock http calls in Unit Testing in C# or .NET

Nitesh Singhal
4 min readMar 16, 2022
Image by Nitesh Singhal

Many time we call external rest API’s from our backend code and we want to write unit test for such code so that we can test our code with the expected response from API. So we have two choice either we use mock API server or we mock http call.

Mock API server is good for integration tests but for Unit tests we should not rely on external services as we can not control external service and thus it might give unexpected behavior on different runs. so another choice we have is to mock the http calls.

It should be fairly simple to mock HttpClient with any mocking library and write Unit tests.

Right ?

So what is the challenge and why it is not as straight forward as it should be.

Let’s understand with example.

Problem

I have MVC frontend app which is calling public API to get random activity.

and to achieve this I have a backend service which does the job of fetching the random activity using public API.

I have a Backendservice class which has logic to fetch data using HttpClient class.

Everything worked perfectly when running as application. Now I want to write Unit test for GetNewActivity method.

I have created a NUnit test project and written a simple unit test to call the GetNewActivity method and to create the instance of BackendService I had to pass an instance of HttpClient.

That’s where I tried to mock the HttpClient, but it did not allowed as it is a class and not interface or abstract class. so we can not mock HttpClient class.

This is the main issue that’s why it is not so simple to mock it.

So how do we mock it then.

Solution

When we have closer look to the HttpClient class, then we see that it takes HttpMessageHandler in the constructor which is abstract class and has SendAsync method which eventually is used for calling external API.

So at the core, we need to mock the response of this SendAsync API and since it is abstract class, we can mock it and override the SendAsync response.

Let’s look at the sample code.

Here we have mocked the HttpMessageHandler class and Setup the SendAsync method to return the expected response.

and when we call GetNewActivity method on BackendService class then it will return response from this mock class instead of actually making http call to external API.

and like that we have successfully mocked the http calls.

PS: This is just one way of doing it. I am sure there are other ways of achieving it.

Demo code at Github

Hope it is helpful.

Happy Coding and Keep learning..!

--

--

Nitesh Singhal

Software architect, Exploring ASP.Net core and containerization technologies