When using the HttpClient in .NET, you might want to add a DelegatingHandler to it. This is useful for adding headers, adding authentication or modifying behavior. Or maybe you want to act on whether or not the response was successful.
Using the ‘arrange-act-assert’ pattern, you cannot call SendAsync with the method being protected. Assuming you have a class CacheHandler which calls a third-party web service, we might want to cache the response as a file when successful, or use the cached file when not successful.
As explained by this article, you can chain multiple DelegatingHandler or HttpMessageHandler. We will leverage this to create our unit tests.
First you want to create two HttpMessageHandlers, which will intercept our requests and return a response we’ve specified. So we also don’t make an unnecessary call to the third-party web service. As that would be called end-to-end tests or integration tests.
For our first test, we will test what happens when the call was unsuccessful, and whether or not the cache was used.
In the code below, you can see we set the NonFoundResponseHandler as the inner handler. This means our request will hit the CacheHandler first, and then attempt to call the third-party web service. As we’ve set the inner handler to the NotFoundResponseHandler, it will return a NotFound response instead rather than calling the third-party web service.
For our second test, we will test what happens when the call was successful, and whether the cache was updated.
First, we’re storing the originally cached file, so we can compare it later. Then we’re setting the OkResponseHandler as the inner handler. This means our request will hit the CacheHandler first, and then attempt to call the third-party web service. As we’ve set the inner handler to the OkResponseHandler, it will return a Ok response rather than calling the third-party web service.
During the assertion, we first verify we’re receiving a unique GUID back as the response. Then we verify the cache was updated by comparing the original content with the new content.