Introduction
When we use HttpClient
to make REST endpoint calls from our applications, the challenge is to make the code unit testable, mainly because, SendAsync
method of HttpClient
class is not virtual. Frameworks like MoQ offer mocking non-virtual methods as well, but for frameworks like NSubstitute, the same is not allowed. Of course, it is a well thought of design decision.
For the purpose of stubbing the HttpClient
calls, we can write a wrapping class with an interface around HttpClient
.
public interface IHttpHelper
{
Task<string> SendAsync(HttpRequestMessage requestMessage);
}
public class HttpWrapper : IHttpHelper
{
public async Task<string> SendAsync(HttpRequestMessage requestMessage)
{
string result;
using (HttpClient _client = new HttpClient())
{
_client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue());
_client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue();
var response = await _client.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
result = await response.Content.ReadAsStringAsync();
}
return result;
}
}
In the unit tests, we can stub like this:
IHttpHelper _httpHelper;
_httpHelper.SendAsync(new HttpRequestMessage()).ReturnsForAnyArgs
(Task.FromResult<string>("your response json for unit testing"));
Point of Interest
The last line of code will also give you an idea about stubbing async
methods that return tasks.