polly - 将 Polly 重试策略添加到模拟的 HttpClient?
问题描述
所以我必须使用一个带有 HttpClient 的库,并且在远程系统发出 429 响应的情况下可能会抛出一个限制异常。
我想测试一个 Polly 策略,它会在请求的秒数内后退,但我不知道如何修改测试以添加 Polly 策略。
我看了这个 SO 问题,但我的情况不同:Test Polly retry policy with moq
这是验证抛出异常的测试。我想使用不会抛出的 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 来制作客户端,在这种情况下,我不确定如何让 THAT 抽出模拟客户端。
解决方案
如果 HttpClientFactory 实例,我无法找到将此类策略注入 HttpClient 的方法,因此您必须像本示例中那样显式使用它。
推荐阅读
- julia - Julia Plots.jl:从系列配方更改标记颜色
- python - 使用 statsmodels OLS 时出现“RecursionError:超出最大递归深度”?
- javascript - Pushing Elements to a JSON Array with Braces
- html - 悬停时显示隐藏的 div
- python-3.x - 关于过滤掉一致的时间序列数据的想法
- c# - 如何在 SQL 中用 Decimal 映射 REAL 数据类型?在 C# 中
- javascript - 在javascript中将三个javascript数组连接到一个数组中
- c++ - 使用无符号而不是有符号的 int 是否更有可能导致错误?为什么?
- reactjs - 没有生命的反应组件会发生什么?
- javascript - 单击包含相关任务的按钮,例如突出显示和滚动