Quantcast
Channel: Active questions tagged retry-logic - Stack Overflow
Viewing all articles
Browse latest Browse all 950

Unit test Polly - Check whether the retry policy is triggered on timeout / error

$
0
0

Problem stmt : I have a service which fetches result from graphql sometime due to server issue the service might throw 500 error

Solution: To resolve the above issue I needed to write a retry logic to retry the service when timeout occurs.

Obstacle : I don't know how to assert the whether the given logic is calling the service three times as specified. Any help is appreciated.

I created a retry policy to retry if the given client is timeout after some time.

public override void ConfigureServices(IServiceCollection services){  services.AddHttpClient<GraphQueryService>(Constants.PPQClient)        .ConfigureHttpClient(client =>        {            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));            client.Timeout = TimeSpan.FromMilliseconds(Constants.ClientTimeOut);        }).AddRetryPolicy();}

RetryLogic :

using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Options;using Polly;namespace PA.Com.Integration{    public static class HttpClientBuilderExtensions    {        public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder builder)        {            var serviceProvider = builder.Services.BuildServiceProvider();            var options = serviceProvider.GetRequiredService<IOptions<RetryOptions>>();            return builder.AddTransientHttpErrorPolicy(b => b.WaitAndRetryAsync(new[]            {                options.Value.RetryDelay1,                options.Value.RetryDelay2,                options.Value.RetryDelay3            }));        }    }}

I'm new to unit testing I believe I called the code to check the timeout but not sure how to assert whether it is called three time on timeout.

Unit Test I tried:

[Fact]public async Task Check_Whether_Given_Policy_Executed_OnTimeout(){    // Given / Arrange     IServiceCollection services = new ServiceCollection();    bool retryCalled = false;    HttpStatusCode codeHandledByPolicy = HttpStatusCode.InternalServerError;   var data =  services.AddHttpClient<GraphQueryService>(Constants.PPQClient)            .ConfigureHttpClient(client =>            {                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                client.Timeout = TimeSpan.FromMilliseconds(Constants.ClientTimeOut);            }).AddRetryPolicy()    .AddHttpMessageHandler(() => new StubDelegatingHandler(codeHandledByPolicy)); //Need to Check the retry logic is called three times. Not sure How to continue after this.    Assert.Equal(codeHandledByPolicy, HttpStatusCode.InternalServerError);    Assert.True(retryCalled);}

Viewing all articles
Browse latest Browse all 950

Trending Articles