【发布时间】:2019-06-17 15:15:10
【问题描述】:
我正在尝试在我的应用程序中正确添加HttpClient,同时还允许模拟客户端工厂以进行单元测试。我使用this 作为资源。
在我的 Startup.cs
services.AddHttpClient<IUploader, Uploader>()
.ConfigurePrimaryHttpMessageHandler(() =>
{
if (somecheckismet)
return new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } };
return new HttpClientHandler();
});
还有我的 Uploader.cs
public class Uploader : IUploader
{
private readonly HttpClient m_httpClient;
public Uploader(HttpClient client)
{
m_httpClient = client;
}
public async Task<string> UploadData(string url, Dictionary<string, string> data)
{
HttpResponseMessage result;
try
{
result = await m_httpClient.PostAsync(url, new FormUrlEncodedContent(data));
if (result.StatusCode != HttpStatusCode.OK)
{
return "Some error message;
}
else
{
return null; // Success!
}
}
catch (Exception ex)
{
return "Uh-oh!";
}
}
}
如您所见,我正在尝试将 HttpClient 依赖注入到 Uploader 中。但是,既然我已经这样做了,我该如何对Uploader 进行单元测试?以前,它可以依赖注入 HttpClientHandler ,它可以被模拟掉。但是,现在由于我尝试使用IHttpClientFactory,看来我必须注入HttpClient。
任何帮助将不胜感激。
【问题讨论】:
-
我用
HttpClienthere做了一个视频。也许它可以提供一些见解或给你一些想法。
标签: c# .net-core dotnet-httpclient