How to unit test C# methods that execute through Polly resilience pipelines?

Asked 21 days ago Updated 21 days ago 128 views

0

Testing code wrapped with resilience strategies requires verifying both success scenarios and failure/retry behaviors under simulated fault conditions.

Unit Testing Pipelines

You can inject custom or dummy resilience pipelines into your domain logic during unit testing using dependency injection or mock builders.

Code Example

[Fact]
public async Task Execute_OnTransientError_RetriesAndSucceeds()
{
    int attempts = 0;
    var pipeline = new ResiliencePipelineBuilder()
        .AddRetry(new RetryStrategyOptions
        {
            MaxRetryAttempts = 2,
            Delay = TimeSpan.Zero
        })
        .Build();

    await pipeline.ExecuteAsync(async ct =>
    {
        attempts++;
        if (attempts == 1)
        {
            throw new HttpRequestException("Transient error");
        }
        await Task.CompletedTask;
    });

    Assert.Equal(2, attempts);
}

0 Answers


Write Your Answer