Polly.Testing package. This package has a range of APIs designed to help you test the setup and combination of resilience pipelines in your user code.
Installation
Begin by adding thePolly.Testing package to your test project:
Basic Usage
Use theGetPipelineDescriptor extension method to get the ResiliencePipelineDescriptor which provides details on the pipeline’s composition:
Testing Generic Pipelines
TheGetPipelineDescriptor extension method is also available for the generic ResiliencePipeline<T>:
Mocking ResiliencePipelineProvider
Consider the following code that might resemble a part of your project:- The
MyApiclass is introduced, representing part of your application that requires resilience support. - The
AddMyApiextension method is also defined, which integratesMyApiinto dependency injection (DI) and sets up the resilience pipeline it uses.
Mocking Example
For unit tests, if you want to assess the behavior ofExecuteAsync, it might not be practical to rely on the entire pipeline, especially since it could slow down tests during failure scenario evaluations. Instead, it’s recommended to mock the ResiliencePipelineProvider<string> and return an empty pipeline:
This example leverages the
NSubstitute library to mock the pipeline provider.Best Practices
Test Configuration
Focus on testing your resilience pipeline configuration and custom delegates, not the internal behavior of Polly strategies.
Use Descriptors
Use
GetPipelineDescriptor() to verify that your pipeline is composed correctly with the right strategies and options.Mock in Unit Tests
Mock
ResiliencePipelineProvider in unit tests to avoid slow tests and focus on testing your application logic.Integration Tests
Use real resilience pipelines in integration tests to verify end-to-end behavior with actual resilience strategies.