Digbyswift Logo Retina

Unit testing HttpClient

Tags:

Unit tests

Published: 23 November 2017

The HttpClient class is great, admit it but it's not entirely clear how to unit test it, and by that we 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 we’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.

Use a mocking framework

We like Moq so that's what has been used below.

This shows fairly clear what’s going on and can easily be manipulated to provide whatever response we like. Sure, we have to jump through a hoop or two to find the virtual SendAsync method but that’s about it.

If we want to verify that the SendAsync() was called duing our test:

Note here that we have to exactly duplicate the call including parameters.

Implementing a mock handler

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 we 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.