How do I test that my pipeline is actually used?
In other words, how to make sure that Execute
/ExecuteAsync
was called. Let me show you two ways.
Notification hooks
To make sure that your resiliency pipeline was called, you can use the notification hooks.
Let me simplify your code like this:
public class MyApi
{
private readonly ResiliencePipeline<int> _pipeline;
private readonly IOrganizationService _service;
public MyApi(ResiliencePipeline<int> pipeline, IOrganizationService service)
=> (_pipeline, _service) = (pipeline, service);
public int Test()
=> _pipeline.Execute(() => _service.Get());
}
public interface IOrganizationService
{
int Get();
}
Then the OnRetry
notification hook usage:
// arrange
var retried = 0;
const int serviceReturnValue = 42;
var serviceMock = new Mock<IOrganizationService>();
serviceMock.Setup(s => s.Get())
.Returns(serviceReturnValue);
var pipeline = new ResiliencePipelineBuilder<int>()
.AddRetry(new RetryStrategyOptions<int>()
{
ShouldHandle = static args => args.Outcome switch {
{ Result: int i } when i == serviceReturnValue => PredicateResult.True(),
_ => PredicateResult.False()
},
OnRetry = args =>
{
retried++;
return default;
}
})
.Build();
// act
var sut = new MyApi(pipeline, serviceMock.Object);
sut.Test();
// assert
Assert.Equal(3, retried);
Basically it counts how many times the retry strategy has been triggered.
ResilienceStrategy
The previous approach can be challenged because you want to make sure that the Execute{Async}
is being called even if no resiliency strategy was trigged.
The solution is to define an AssertionStrategy
:
public class AssertionStrategyOptions: ResilienceStrategyOptions
{
public bool HasExecuted { get; set; }
}
public class AssertionStrategy: ResilienceStrategy
{
private readonly AssertionStrategyOptions _options;
public AssertionStrategy(AssertionStrategyOptions options)
{
_options = options;
}
protected override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(
Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback,
ResilienceContext context,
TState state)
{
_options.HasExecuted = true;
return await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext);
}
}
This strategy does nothing, just sets the HasExecuted
flag to true
if the Execute{Async}
was called.
The usage is this simple:
// arrange
...
var assertionOptions = new AssertionStrategyOptions();
var pipeline = new ResiliencePipelineBuilder<int>()
.AddRetry(new RetryStrategyOptions<int>()
{
...
})
.AddStrategy(context => new AssertionStrategy(assertionOptions))
.Build();
// act
var sut = new MyApi(pipeline, serviceMock.Object);
sut.Test();
// assert
Assert.True(assertionOptions.HasExecuted);