c# - 如何使用 Moq 从 IHttpClientFactory 模拟 HTTPClient 并结合 .NET Core 中的 Polly 策略

标签 c# .net-core httpclient moq polly

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

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 客户端?

编辑:Mock 意味着能够模拟 HTTP 的请求。应按照定义应用该策略。

最佳答案

正如 stackoverflow 上的许多其他帖子所述,您不会模拟 HTTP 客户端本身,而是模拟 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 客户端,您可以执行以下操作:

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

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

关于c# - 如何使用 Moq 从 IHttpClientFactory 模拟 HTTPClient 并结合 .NET Core 中的 Polly 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69945866/

相关文章:

java - postData 无法解析为类型

c# - 在 WPF 的 ContentControl 中托管 ViewModel

c# - ProcessStartInfo.EnvironmentVariables 和 ProcessStartInfo.Environment 之间有什么区别

c# - log4net-RollingFileAppender-XmlLayoutSchemaLog4j 未登录 .Net Core 3

c# - 没有注册类型 'Microsoft.AspNetCore.Identity.UserManager` 1[Microsoft.AspNetCore.Identity.IdentityUser]' 的服务

Android HttpClient 性能

c# - LINQ 返回列表中与另一个列表中的任何名称(字符串)匹配的项目

C# 使用非托管数据序列化类

C# 将文档从 mongodb 读取到 JSON 中并尝试获取值

angular - Angular `HttpClient` `.get()` 泛型可以有非简单的属性类型吗? (例如 `string` 或 `number` 除外)