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 if we can somehow avoid using 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
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:
And in our test class:
Here we simply create a mock version of
FakeHttpMessageHandler and setup the
Send method and pass that into our
HttpClient when we create it, and finally 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.