首页 > 解决方案 > 将 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 抽出模拟客户端。

标签: polly

解决方案


如果 HttpClientFactory 实例,我无法找到将此类策略注入 HttpClient 的方法,因此您必须像本示例中那样显式使用它。


推荐阅读