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.
thats exactly what was mentioned on the github issue. This blog post for what what??
Haters gonna hate. Looser much Mr Curious.
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
Do you have the complete code demo so I can try it out?
In this project: https://github.com/HamidMosalla/FreelancerBlog there is a class in test project called “CaptchaValidatorTests”, but I’ve commented it out since the logic for sut has moved to “ValidateCaptchaQueryHandler” class.
This was exactly what I was looking for!
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”);
}
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.