Created
July 30, 2020 00:20
-
-
Save josephwoodward/c45d88033dadbd341ece7250da136cca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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