-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Unit testing with Polly
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.
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.
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 thathttpClient.GetAsync(url)
is called the multiple times you expect.
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.
Other questions about unit-testing? Post an issue on the issues board.
- Home
- Polly RoadMap
- Contributing
- Transient fault handling and proactive resilience engineering
- Supported targets
- Retry
- Circuit Breaker
- Advanced Circuit Breaker
- Timeout
- Bulkhead
- Cache
- Rate-Limit
- Fallback
- PolicyWrap
- NoOp
- PolicyRegistry
- Polly and HttpClientFactory
- Asynchronous action execution
- Handling InnerExceptions and AggregateExceptions
- Statefulness of policies
- Keys and Context Data
- Non generic and generic policies
- Polly and interfaces
- Some policy patterns
- Debugging with Polly in Visual Studio
- Unit-testing with Polly
- Polly concept and architecture
- Polly v6 breaking changes
- Polly v7 breaking changes
- DISCUSSION PROPOSAL- Polly eventing and metrics architecture