I have the following code using an HttpClient. I'm new to C# and would like to learn how to unit test my HttpClient but am not sure where to begin. Here is my code:
protected override async Task PopulateData()
{
using (var client = new HttpClient())
{
var token = "private token";
var requestUrl = api_url_here;
var authenticatedRequestUrl = requestUrl + $"{token}";
var response = await client.GetAsync(authenticatedRequestUrl);
var stringResult = await response.Content.ReadAsStringAsync();
// do something
}
}
I've seen lots of different articles suggesting different ways to unit test but I am unsure as to how to use them properly. For example, I've seen this unit test pattern on many websites:
[Test]
public async Task MockingHTTP()
{
var requestUri = new Uri("");
var expectedResponse = "Response";
var mockHandler = new Mock<HttpMessageHandler>();
mockHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage(Net.HttpStatusCode.OK));
var httpClient = new HttpClient(mockHandler.Object);
var result = await httpClient.GetStringAsync(requestUri).ConfigureAwait(false);
Assert.AreEqual(expectedResponse, result);
}
}
However I don't know how to apply this approach to my code. Please can someone point my in the right direction in order to successfully unit test the HttpClient?
PopulateDatato make sure it does its work properly. That's just basic unit testing - mock the dependencies.