如何使用 Moq 从 IHttpClientFactory 结合 .NET Core 中的 Polly 策略模拟 HTTPClient [英] How to Mock HTTPClient from IHttpClientFactory combined with Polly policies in .NET Core using Moq

查看:22
本文介绍了如何使用 Moq 从 IHttpClientFactory 结合 .NET Core 中的 Polly 策略模拟 HTTPClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 IHttpClientFactory 创建了一个 HTTP 客户端并附加了一个 Polly 策略(需要 Microsoft.Extensions.Http.Polly),如下所示:

I create a HTTP Client using IHttpClientFactory and attach a Polly policy (requires Microsoft.Extensions.Http.Polly) as follows:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;

IHost host = new HostBuilder()
    .ConfigureServices((hostingContext, services) =>
    {
        services.AddHttpClient("TestClient", client =>
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        })
        .AddPolicyHandler(PollyPolicies.HttpResponsePolicies(
            arg1, 
            arg2,
            arg3));
    })
    .Build();

IHttpClientFactory httpClientFactory = host.Services.GetRequiredService<IHttpClientFactory>();

HttpClient httpClient = httpClientFactory.CreateClient("TestClient");

如何使用 Moq 模拟此 HTTP 客户端?

How can I mock this HTTP Client using Moq?

Mock 意味着能够模拟 HTTP 的请求.应按定义应用该政策.

Mock means to be able to mock the requests of the HTTP. The policy should be applied as defined.

推荐答案

如 stackoverflow 上的许多其他帖子所述,您不是模拟 HTTP 客户端本身,而是模拟 HttpMessageHandler:

As described in many other posts on stackoverflow you don't mock the HTTP Client itself but HttpMessageHandler:

Mock<HttpMessageHandler> handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
    .Protected()
    .Setup<Task<HttpResponseMessage>>(
        "SendAsync",
        ItExpr.IsAny<HttpRequestMessage>(),
        ItExpr.IsAny<CancellationToken>()
    )
    .ReturnsAsync(new HttpResponseMessage()
    {
        StatusCode = HttpStatusCode.OK,
        Content = new StringContent(response)
    });

为了最终拥有一个带有模拟 HttpMessageHandler 和 Polly 策略的 HTTP 客户端,您可以执行以下操作:

To then in the end have a HTTP Client with the mocked HttpMessageHandler as well as the Polly Policy you can do the following:

IServiceCollection services = new ServiceCollection();
services.AddHttpClient("TestClient")
    .AddPolicyHandler(PollyPolicies.HttpResponsePolicies(arg1, arg2, arg3))
    .ConfigurePrimaryHttpMessageHandler(() => handlerMock.Object);

HttpClient httpClient =
    services
        .BuildServiceProvider()
        .GetRequiredService<IHttpClientFactory>()
        .CreateClient("TestClient");

这篇关于如何使用 Moq 从 IHttpClientFactory 结合 .NET Core 中的 Polly 策略模拟 HTTPClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆