Click here to Skip to main content
15,895,817 members
Articles / DevOps / Unit Testing
Tip/Trick

Stubbing HttpClient Library

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
17 Apr 2016CPOL 10.8K   1   1
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)


Written By
Software Developer (Senior)
India India
Hi, I am Purbasha and I have been into web development, clean code promotion and benchmarking new Azure offerings since quite a while now. I am here to share my learnings and solutions/hacks that I keep collecting with my experience.

Comments and Discussions

 
Suggestionwrappers are good Pin
Member 1433745927-Apr-19 7:35
Member 1433745927-Apr-19 7:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.