Skip to content

Unit testing with Polly

reisenberger edited this page Oct 15, 2016 · 30 revisions

People often ask how to unit-test code wrapped in Polly policies.

Say originally you had:

HttpResponse result = await httpClient.GetAsync(url);

To give a simple example, say you update to:

RetryPolicyAsync retryPolicy = Policy.Handle<HttpException>().RetryAsync(1);
HttpResponse result = await retryPolicy.ExecuteAsync(() => httpClient.GetAsync(url));

How to test? It depends what you're trying to test.

Testing that GetAsync(url) is still invoked at least once

If you had an existing unit-test that mocked out httpClient (for example with Moq) and verified GetAsync(...) was called at least once when the original code was traversed, the same test should suffice. There's no need to mock or stub the Polly policy: it's lightweight; there's nothing to be gained by mocking or stubbing it.

Testing that GetAsync(url) is invoked a second time if the given exception is thrown

You may want reassurance more broadly that the Polly policy will do what it says. The best answer is: there's no need for your own units tests for this. The Polly codebase has (as at v5.0) 1000+ tests exercising the policies so we have done this for you.

If you do want to construct a test verifying policy operation, an approach (given the above example) could be:

  • Mock httpClient.GetAsync(url) and set up mock behaviour so that it counts each time it's invoked (invocations++ or similar), then throws.
  • Don't mock the policy: it's the system-under-test.
  • Assert on the eventual count of invocations to prove that httpClient.GetAsync(url) is called the multiple times you expect.

Further tests

Quickly one can think of many further tests:

  • If it throws fewer number of times than retries can handle, overall I should get a result not an exception.
  • If it throws greater number of times than retries can handle, overall I should get the exception.
  • If it throws an exception not handled, I should get the exception, not any retries.
  • (etc)

The technique outlined in the previous section can be extended to cover all these scenarios, but again: Polly has all these scenarios and more already extensively tested.

Questions?

Other questions about unit-testing? Post an issue on the issues board.

Clone this wiki locally