Skip to content

Instantly share code, notes, and snippets.

@josephwoodward
Created July 30, 2020 00:20
Show Gist options
  • Save josephwoodward/c45d88033dadbd341ece7250da136cca to your computer and use it in GitHub Desktop.
Save josephwoodward/c45d88033dadbd341ece7250da136cca to your computer and use it in GitHub Desktop.
private static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == HttpStatusCode.ServiceUnavailable)
.RetryAsync(3);
}
[Fact]
public async Task ShouldRetryTransientErrors()
{
// Arrange
int numberOfRequests = 0;
var options = new HttpClientInterceptorOptions {ThrowOnMissingRegistration = true};
new HttpRequestInterceptionBuilder()
.Requests()
.ForHttps()
.ForHost("bbc.co.uk")
.ForPath("/news")
.Responds()
.WithStatus(HttpStatusCode.ServiceUnavailable)
.WithInterceptionCallback(_ => numberOfRequests++)
.RegisterWith(options);
var collection = new ServiceCollection()
.AddHttpClient("bbc_client")
.AddPolicyHandler(GetRetryPolicy())
.AddHttpMessageHandler(options.CreateHttpMessageHandler)
.Services
.BuildServiceProvider();
var httpClient = collection.GetService<IHttpClientFactory>().CreateClient("bbc_client");
// Act
var response = await httpClient.GetAsync("https://bbc.co.uk/news");
// Assert
numberOfRequests.ShouldBe(4);
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment