Skip to content

Unit testing with Polly

reisenberger edited this page Jul 13, 2016 · 29 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. The Polly codebase has 650+ tests exercising the policies. If you want to though, an approach could be:

  • Mock httpClient.GetAsync(url) and set up mock behaviour so that it counts how many times 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 I have configured, 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.

The technique outlined above can be extended to cover all these scenarios, but again, the best answer is: Polly has all these scenarios already extensively tested.

Questions?

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

Clone this wiki locally