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.

Did you like this?
Tip Hamid Mosalla with Cryptocurrency

Donate Bitcoin to Hamid Mosalla

Scan to Donate Bitcoin to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to Hamid Mosalla

Scan to Donate Bitcoin Cash to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to Hamid Mosalla

Scan to Donate Ethereum to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to Hamid Mosalla

Scan to Donate Litecoin to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to Hamid Mosalla

Scan to Donate Monero to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to Hamid Mosalla

Scan to Donate ZCash to Hamid Mosalla
Scan the QR code or copy the address below into your wallet to send some ZCash:
Share...
  • 7
    Shares
 

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.