Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps / unit-testing

Stubbing HttpClient Library

4.80/5 (2 votes)
18 Apr 2016CPOL 11K  
Stubbing HttpClient calls using NSubstitute framework

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.

C#
public interface IHttpHelper
{
    Task<string> SendAsync(HttpRequestMessage requestMessage);
}
C#
public class HttpWrapper : IHttpHelper
{
    public async Task<string> SendAsync(HttpRequestMessage requestMessage)
    {
        string result;
        using (HttpClient _client = new HttpClient())
        {
            _client.DefaultRequestHeaders.Accept.Add
            (new MediaTypeWithQualityHeaderValue(/*your content type*/));
            _client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(/*add authorization header values here*/);

            var response = await _client.SendAsync(requestMessage);
            response.EnsureSuccessStatusCode();

            result = await response.Content.ReadAsStringAsync();
        }
        return result;
    }
 }

In the unit tests, we can stub like this:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)