This is not a fully working solution, just parts of the code to make the question cleaner and more readable.
I have read the Polly's documentation here, however I really need to test whether the following TimeoutPolicy's onTimeoutAsync
delegate is being hit (also, in case of wrapping TimeoutPolicy along with RetryPolicy - how many TIMES it has been hit) after the httpClient times out:
public static TimeoutPolicy<HttpResponseMessage> TimeoutPolicy
{
get
{
return Policy.TimeoutAsync<HttpResponseMessage>(1, onTimeoutAsync: (context, timeSpan, task) =>
{
Console.WriteLine("Timeout delegate fired after " + timeSpan.TotalMilliseconds);
return Task.CompletedTask;
});
}
}
TimeoutPolicy is set to timeout after 1 second of not receiving anything from HTTP client (HttpClient's mock is delayed for 4 seconds as shown below)
var httpMessageHandler = new Mock<HttpMessageHandler>();
httpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.Callback(() => Thread.Sleep(4000))//Delayed here
.Returns(() => Task.FromResult(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("Some response body", Encoding.UTF8, "text/xml")
}));
var httpClient = new HttpClient(httpMessageHandler.Object);
Policies are mocked to be able to call .Verify() on it for Assertion:
var mockedPolicies = new Mock<Policies>();
I execute the call with a mocked HTTP Client and a mocked Timeout policy:
await mockedPolicies.Object.TimeoutPolicy.ExecuteAsync(ct => _httpClient.PostAsync("", new StringContent("Some request body"), ct), CancellationToken.None);
Assertion:
mockedPolicies.Verify(p => p.TimeoutDelegate(It.IsAny<Context>(), It.IsAny<TimeSpan>(), It.IsAny<Task>()), Times.Exactly(1));
However, test outcome says it has been called 0 times instead of 1. Thank you for any answers.