I am trying to properly add HttpClient in my app while also allowing for mocking away the client factory for unit testing purposes. I am using this as as resource.
In my Startup.cs
services.AddHttpClient<IUploader, Uploader>()
.ConfigurePrimaryHttpMessageHandler(() =>
{
if (somecheckismet)
return new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } };
return new HttpClientHandler();
});
And my 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!";
}
}
}
As you can see I am trying to dependency inject HttpClient into the Uploader. However, now that I've done this, how do I go about unit testing the Uploader? Previously, it would have worked to dependency inject HttpClientHandler which can be mocked away. However, now since I am trying to use IHttpClientFactory, it seems that I have to inject HttpClient.
Any help would be greatly appreciated.