【发布时间】:2021-11-12 16:10:37
【问题描述】:
我使用 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 客户端?
编辑:模拟意味着能够模拟 HTTP 的请求。应按定义应用该政策。
【问题讨论】:
-
你想测试什么?是否要测试该策略?
-
好的,现在很清楚了。如果您想测试 polly,那么我建议将其作为集成测试进行,正如我在 here 中描述的那样。
标签: c# .net-core httpclient moq polly