【问题标题】:Adding Polly retry policy to a mocked HttpClient?将 Polly 重试策略添加到模拟的 HttpClient?
【发布时间】:2020-03-06 23:44:44
【问题描述】:

所以我必须使用一个接受 HttpClient 的库,并且在远程系统发出 429 响应的情况下可能会抛出一个限制异常。

我想测试一个 Polly 策略,它会在请求的秒数内后退,但我不知道如何修改测试以添加 Polly 策略。

我看了这个 SO question,但我的情况不同:Testing 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 来制作客户端,在这种情况下我不确定如何制作抽出模拟客户端。

【问题讨论】:

标签: polly


【解决方案1】:

如果 HttpClientFactory 实例,我找不到将这种策略注入 HttpClient 的方法,所以you'll have to use it explicitly like in this example.

【讨论】:

    猜你喜欢
    • 2022-10-19
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多