The HttpClient class is great, admit it but it's not entirely clear how to unit test it, and by that I mean how to unit test the responses generated by it. This should be straightforward right? Well, mostly. The trick is not to mock the class itself but mock the HttpMessageHandler that it uses.
There are several ways to achieve this but I’ve outlined two here. Consider them opposite sides to the same coin. The first uses Moq and the second abstracts the HttpMessageHandler directly. IU like both approaches.
I like Moq so that's what I'm using below.
I like this as it’s fairly clear what’s going on and I can easily manipulate it to provide whatever response I like. Sure, I have to jump through a hoop or two to find the virtual SendAsync method but that’s about it.
If I want to verify that the SendAsync() was called duing my test:
Note here that I have to exactly duplicate the call including parameters.
This way involves writing an implementation of the HttpMessageHandler instead of using a framework and asking HttpClient to use this instead of the default.
This way you have much the same functionality as the Moq approach but the code is a little clearer. In this scenario in your test you have to load in your mock handler:
You can till verify that SendAsync() was called (or was called the correct number of times) using the CalledTimes property.
This approach has advantages over the Moq approach in that I think it is much clearer to a reader what is going on. You can also eapnd on the mock implementation as you need to introduce further test functionality like throwing an error.
Tags: Unit tests
Published: 23 November 2017