Integration testing your Polly policies with HttpClient Interception

Posted on Thursday, 30 Jul 2020

In my previous post I introduced HttpClientInterception, a hugely versatile .NET library that I've had great success with. In the post I demonstrated how you can use it to stub remote HTTP service dependencies within your application to ease testing. Towards the end of the post I demonstrated how it integrated with IHttpClientFactory via the IHttpMessageHandlerBuilderFilter interface, enabling you to apply additional HttpMessageHandlers to your HttpClients generated via IHttpClientFactory.

In this post I want to go further by demonstrating how you can use this same approach to integration test your Polly policies and how they integrate with the HttpClient.

Note: If you haven't read my previous post then I would recommend doing so as this post leans a lot on content discussed in it.

Integration testing your Polly policies with HttpClient

One of the more common approaches to configuring your Polly policies with an HttpClient is via the Microsoft.Extensions.Http.Polly package.

This package builds onto of the IHttpClientBuilder interface allowing you to chain Polly policies with the AddPolicyHandler extension method, like so:

The .AddPolicyHandler method takes an async Polly Policy and creates an HttpMessageHandler that gets added to the HttpClient message handler pipeline:

Integration testing a Polly Retry Policy

Using this same approach we can create our HttpClientInterception configuration, but this time use the WithInterceptionCallback(Action<HttpRequestMessage> action) method, which gets executed after every matched request, to perform operations like count the number of retries made (this will include the initial request):

Conclusion

Hopefully this and the previous post have demonstrated just how versatile the HttpClientInterception can be, from stubbing simple requests from dependencies to integration testing Polly policies as I've demonstrated above.