1

I'm using polly (8.0.0) to add some resilience to an api (which in this case calls a D365 service).

public class MyApi
{
    private readonly ResiliencePipeline pipeline;
    private readonly IOrganizationService service;

    public MyApi(ResiliencePipelineProvider<string> provider, IOrganizationService service)
    {
        this.pipeline = provider.GetPipeline("retry-pipeline");
        this.service = service;
    }

    public List<string> GetSomething(QueryByAttribute query)
    {
        var result = this.pipeline.Execute(() => service.RetrieveMultiple(query));
        return result.Entities.Cast<string>().ToList();
    }
}

The docs (https://www.pollydocs.org/advanced/testing.html) describe how you can inject in a ResiliencePipelineProvider into your api to access the pipeline. This can be mocked, e.g. to return a ResiliencePipeline.Empty, it describes, and the details of your pipeline configuration can be tested as well.

However - how do I test that my pipeline is actually used? ResiliencePipeline can't be mocked with moq.

Type to mock (ResiliencePipeline) must be an interface, a delegate, or a non-sealed, non-static class

4
  • How would the subject under test behave differently in the cases where the pipeline would be used and where not? What input and environment would have to be set up to trigger it being perceivably used?
    – Fildor
    Commented Aug 19 at 9:28
  • ^^ i.e. let's say you have a retry 3x. Then, if I set up the test so requests will fail once and then succeed, then sut shoud succeed overall if resilience is in effect, right? Same for fail twice. ...
    – Fildor
    Commented Aug 19 at 9:32
  • If my GetSomething() code only used the service directly, and ignored the pipeline, then the api would not have resilience. I guess I'm simply trying to put some unit test coverage in place to show that the resilience pipeline is used.
    – Andy Cooke
    Commented Aug 19 at 9:33
  • Exactly, so you need to make the "target" behave predictably "faulty", so you can know when the resilience should have been triggered but was not. If that's the case, then it either wasn't in effect at all or setup incorrectly. Now, if you additionally test the pipeline behavior and you thus know, it is configured correctly, then it can only not have been in effect.
    – Fildor
    Commented Aug 19 at 9:36

2 Answers 2

2

I was inspired by this question to write a blog post. To summarize, in it I describe why it's often a better option to apply the Decorator pattern when it comes to cross-cutting concerns like fault tolerance and resiliency, like the services provided by Polly.

The article also describes how much easier unit testing becomes. If, on the other hand, you don't want to make that change, you can also use the technique described in the Polly documentation:

[Theory]
[InlineData("foo", "bar", "baz")]
[InlineData("qux", "quux", "corge")]
[InlineData("grault", "garply", "waldo")]
public void GetSomething(params string[] expected)
{
    var provider = new Mock<ResiliencePipelineProvider<string>>();
    provider
        .Setup(p => p.GetPipeline("retry-pipeline"))
        .Returns(ResiliencePipeline.Empty);
    var service = new Mock<IOrganizationService>();
    service
        .Setup(s => s.RetrieveMultiple(new QueryByAttribute()))
        .Returns(new QueryResult(expected));
    var sut = new MyApi(provider.Object, service.Object);

    var actual = sut.GetSomething(new QueryByAttribute());

    Assert.Equal(expected, actual);
}

This test uses ResiliencePipeline.Empty to effectively ignore the injected ResiliencePipeline. Instead, this test verifies that the rest of MyApi works as intended.

How do you test that that the ResiliencePipeline works as intended, then?

Well, you're using a third-party library. An important point of using a third-party library is to trust that it works as advertised. Thus, you shouldn't be testing third-party software.

If you feel that must cover the Polly configuration by one or more unit tests, you can use the suggestion from the documentation. Here, I've tested the example code from my article:

[Fact]
public void InspectPipeline()
{
    var actual = ResilientOrganizationService.CreatePipeline();

    var descriptor = actual.GetPipelineDescriptor();
    var options = descriptor.Strategies.Select(s => s.Options);
    var restryOptions = Assert.Single(options.OfType<RetryStrategyOptions>());
    Assert.Equal(4, restryOptions.MaxRetryAttempts);
    var timeoutOptions = Assert.Single(options.OfType<TimeoutStrategyOptions>());
    Assert.Equal(TimeSpan.FromSeconds(1), timeoutOptions.Timeout);
}

This is really a prime example of Structural Inspection if I ever saw one. Even so, it's a technique that I don't use much these days, since I'm not convinced that it offers much advantage over just looking that the actual configuration code, but this ultimately depends on where on the risk spectrum you find yourself.

1

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.