Refactoring code to allow for unit testing of Http

2019-08-18 13:57发布

I am dealing with a piece of code that looks like this:

public class Uploader : IUploader
{
    public Uploader()
    {
        // assign member variables to dependency injected interface implementations
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {
            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);

            result = await client.PostAsync(url, new FormUrlEncodedContent(data));

            if (result.StatusCode != HttpStatusCode.OK)
            {
                return "Some Error Message";
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            // do some fancy stuff here
        }
    }
}

I am trying to unit test the Upload function. In particular, I need to mock the HttpClient. After reading the other answers on here and these two articles, I know that one of the better ways to solve this is to mock the HttpMessageHandler instead and pass that to HttpClient and have it return whatever I want.

So, I started along that path by first passing in HttpClient in the constructor as a dependency:

public class Uploader : IUploader
{
    private readonly HttpClient m_httpClient; // made this a member variable

    public Uploader(HttpClient httpClient) // dependency inject this
    {
        m_httpClient = httpClient;
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {
            var handler = new HttpClientHandler();

            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)
        {
            // do some fancy stuff here
        }
    }
}

and adding: services.AddSingleton<HttpClient>(); to the ConfigureServices method of Startup.cs.

But now I face a slight issue where the original code specifically creates a HttpClientHandler to pass in. How then do I refactor that to take in a mockable handler?

2条回答
成全新的幸福
2楼-- · 2019-08-18 14:13

I find the simplest way is to continue using HttpClient, but pass in a mocking HttpClientHandler such as https://github.com/richardszalay/mockhttp

Code sample from the link above:

var mockHttp = new MockHttpMessageHandler();

mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}");

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

var response = await client.GetAsync("http://localhost/api/user/1234");

var json = await response.Content.ReadAsStringAsync();

Console.Write(json); // {'name' : 'Test McGee'}

The Dependency Injection framework built into .NET Core ignores internal constructors, so it will call the parameter-less constructor in this scenario.

public sealed class Uploader : IUploader
{
    private readonly HttpClient m_httpClient;

    public Uploader() : this(new HttpClientHandler())
    {
    }

    internal Uploader(HttpClientHandler handler)
    {
        m_httpClient = new HttpClient(handler);
    }

    // regular methods
}

In your unit tests, you can use the constructor accepting the HttpClientHandler:

[Fact]
public async Task ShouldDoSomethingAsync()
{
    var mockHttp = new MockHttpMessageHandler();

    mockHttp.When("http://myserver.com/upload")
        .Respond("application/json", "{'status' : 'Success'}");

    var uploader = new Uploader(mockHttp);

    var result = await uploader.UploadAsync();

    Assert.Equal("Success", result.Status);
}

Normally I'm not a big fan of having an internal constructor to facilitate testing, however, I find this more obvious and self-contained than registering a shared HttpClient.

HttpClientFactory might be another good option, but I haven't played around with that too much, so I'll just give info on what I've found useful myself.

查看更多
\"骚年 ilove
3楼-- · 2019-08-18 14:19

One way would be to abstract your HTTP functionality into a service i.e. HttpService which implements an interface of IHttpService:

IHttpService

public interface IHttpService
{
    Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null);
}

HttpService

public class HttpService : IHttpService
{
    private static HttpClient _httpClient;

    private const string MimeTypeApplicationJson = "application/json";

    public HttpService()
    {
        _httpClient = new HttpClient();
    }

    private static async Task<HttpResponseMessage> HttpSendAsync(HttpMethod method, Uri url, string payload,
        Dictionary<string, string> headers = null)
    {
        var request = new HttpRequestMessage(method, url);
        request.Headers.Add("Accept", MimeTypeApplicationJson);

        if (headers != null)
        {
            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }
        }

        if (!string.IsNullOrWhiteSpace(payload))
            request.Content = new StringContent(payload, Encoding.UTF8, MimeTypeApplicationJson);

        return await _httpClient.SendAsync(request);
    }

    public async Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null)
    {
        return await HttpSendAsync(HttpMethod.Post, url, payload, headers);
    }
}

Add to your services:

services.AddSingleton<IHttpService, HttpService>();

In your class you would then inject IHttpService as a dependency:

public class Uploader : IUploader
{
    private readonly IHttpService _httpService; // made this a member variable

    public Uploader(IHttpService httpService) // dependency inject this
    {
        _httpService = httpService;
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {

            result = await _httpService.PostAsync(new Uri(url), data);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                return "Some Error Message";
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            // do some fancy stuff here
        }
    }
}

You could then use Moq to mock HttpService in your unit test:

[TestClass]
public class UploaderTests
{
    private Mock<IHttpService> _mockHttpService = new Mock<IHttpService>();

    [TestMethod]
    public async Task WhenStatusCodeIsNot200Ok_ThenErrorMessageReturned()
    {
        // arrange  
        var uploader = new Uploader(_mockHttpService.Object);
        var url = "someurl.co.uk";
        var data = "data";

        // need to setup your mock to return the response you want to test
        _mockHttpService
            .Setup(s => s.PostAsync(url, data))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError));

        // act
        var result = await uploader.Upload(new Uri(url), data);

        // assert
        Assert.AreEqual("Some Error Message", result);      
    }

    [TestMethod]
    public async Task WhenStatusCodeIs200Ok_ThenNullReturned()
    {
        // arrange  
        var uploader = new Uploader(_mockHttpService.Object);
        var url = "someurl.co.uk";
        var data = "data";

        // need to setup your mock to return the response you want to test
        _mockHttpService
            .Setup(s => s.PostAsync(new Uri(url), data))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));

        // act
        var result = await uploader.Upload(url, data);

        // assert
        Assert.AreEqual(null, result);      
    }
}
查看更多
登录 后发表回答