将 Polly 重试策略添加到模拟的 HttpClient 中?
Adding Polly retry policy to a mocked HttpClient?
所以我必须使用一个带有 HttpClient 的库,并且可能会在来自远程系统的 429 响应的情况下抛出限制异常。
我想测试一个 Polly 策略,它会后退请求的秒数,但我不知道如何修改测试以添加 Polly 策略。
我看了这个 SO 问题,但我的情况不同:
下面是验证抛出异常的测试。我想制作一个不会抛出 Polly 重试策略的不同版本。
using Moq;
using Moq.Protected;
using Polly;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
[TestClass]
public class SIGSClientTests
{
[TestMethod]
public async Task SigsThrowsOn429()
{
var resp = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
Content = new StringContent("{}"),
};
resp.Headers.Add("Retry-After", "42");
var mockMessageHandler = new Mock<HttpMessageHandler>();
mockMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(resp);
var client = new HttpClient(mockMessageHandler.Object);
// Presumably I can create a Polly retry policy here, and add it to the HttpClient?
// And then add a 2nd OK response and get rid of the try-catch?
Uri substrateurl = new Uri("https://substrate.office.com/");
try {
await SIGSClient.Instance.PostAsync(client, substrateurl, new UserInfo(), "faketoken", new Signal(), Guid.NewGuid());
}
catch (SigsThrottledException e)
{
Assert.AreEqual(e.RetryAfterInSeconds, (uint)42);
}
}
我很清楚如何创建 Polly 重试策略,但似乎我能找到的所有单元测试示例都希望我使用 HttpClientFactory 来创建客户端,在这种情况下我不确定如何制作模拟客户端。
我无法找到将此类策略注入 HttpClient if HttpClientFactory 实例的方法,因此
所以我必须使用一个带有 HttpClient 的库,并且可能会在来自远程系统的 429 响应的情况下抛出限制异常。
我想测试一个 Polly 策略,它会后退请求的秒数,但我不知道如何修改测试以添加 Polly 策略。
我看了这个 SO 问题,但我的情况不同:
下面是验证抛出异常的测试。我想制作一个不会抛出 Polly 重试策略的不同版本。
using Moq;
using Moq.Protected;
using Polly;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
[TestClass]
public class SIGSClientTests
{
[TestMethod]
public async Task SigsThrowsOn429()
{
var resp = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
Content = new StringContent("{}"),
};
resp.Headers.Add("Retry-After", "42");
var mockMessageHandler = new Mock<HttpMessageHandler>();
mockMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(resp);
var client = new HttpClient(mockMessageHandler.Object);
// Presumably I can create a Polly retry policy here, and add it to the HttpClient?
// And then add a 2nd OK response and get rid of the try-catch?
Uri substrateurl = new Uri("https://substrate.office.com/");
try {
await SIGSClient.Instance.PostAsync(client, substrateurl, new UserInfo(), "faketoken", new Signal(), Guid.NewGuid());
}
catch (SigsThrottledException e)
{
Assert.AreEqual(e.RetryAfterInSeconds, (uint)42);
}
}
我很清楚如何创建 Polly 重试策略,但似乎我能找到的所有单元测试示例都希望我使用 HttpClientFactory 来创建客户端,在这种情况下我不确定如何制作模拟客户端。
我无法找到将此类策略注入 HttpClient if HttpClientFactory 实例的方法,因此