Mock HttpClient Without Wrapper Using HttpMessageHandler

There is a lot of discussion on github about why HttpClient doesn’t have an interface. Despite the long winded discussion on github about the subject, I think mocking the HttpClient isn’t that hard. We can solve this problem with a wrapper, but wrappers are not a good idea when we can avoid them. Partly because it will be an extra unnecessary layer of abstraction that we have to test and maintain, and should be avoided if possible in my opinion. So in this post I’ll discuss how I mocked the HttpClient with the help of HttpMessageHandler.

Using HttpClient

Suppose we have a class that uses the HttpClient (notice that I removed the parts that was not relevant):

In this class, all we have to do is to pass it in the constructor as a dependency, and register it in our Asp.Net Core container (services.AddSingleton<HttpClient>();). I usually share an instance of HttpClient across the entire application and here’s why if you’re curious.

Next step is to create a fake HttpMessageHandler, we later use this class in our test class and pass it to our test HttpClient:

Testing Method Dependent On HttpClient

Here we simply create a mock version of FakeHttpMessageHandler and setup the Send method and pass that into our HttpClient when we create it. Finally I pass the instance of HttpClient into constructor of our class. I think it wasn’t that hard, this code also can be refactored to be more readable and reusable across our code base.

Share...
 

Hamid Mosalla

Hi, I'm Hamid Mosalla, I'm a software developer, indie cinema fan and a classical music aficionado. Here I write about my experiences mostly related to web development and .Net.

 

8 thoughts on “Mock HttpClient Without Wrapper Using HttpMessageHandler

  1. I must say it was hard to find your site in google. You write interesting articles but
    you should rank your website higher in search engines.
    If you don’t know 2017 seo techniues search on youtube: how
    to rank a website Marcel’s way

  2. Getting this error while running test
    Message: System.InvalidOperationException : Handler did not return a response message.

    what exactly do we have to do here
    public virtual HttpResponseMessage Send(HttpRequestMessage request)
    {
    throw new NotImplementedException(“Remember to setup this method with your mocking framework”);
    }

    1. It really depend on your test, but whatever’s needed to simulate our situation. In this case we return HttpResponseMessage with needed status code and content that takes our program to specific branch of our program which need to be tested.

Leave a Reply

Your email address will not be published. Required fields are marked *