When writing unit tests that involve testing classes that use HttpClient things can get tricky. HttpClient does not implement any interface and mocking out HttpClient can be complex. However, HttpClient itself is dependent on implementations of the HttpMessageHandler type to do the actual work. We can use this to our advantage by creating our own custom message handlers by inheriting from HttpMessageHandler and then supplying the derived type to the HttpClient that is involved in the unit test.
For example in the code below we have defined our own custom HTTP message handler that returns a 401 Unauthorized when called with any request:
We can then use this custom HTTP message handler in our HttpClient by passing an instance on the constructor:
Usually when dealing with HTTP APIs we just care about the response status code and/or content. We could generalize the approach above even further by creating a fake response handler that takes the required HTTP status code and content on it’s constructor and so can be used across many different unit test scenarios.
With this knowledge you can now write unit tests that test what your application does in particular scenarios dependent on what response is returned from the HttpClient. Of course all of this assumes that your class under test takes an injected instance of HttpClient and does not create an instance itself. You are injecting your HttpClient instance, right? ;-)