C# – How to use FakeItEasy with HttpClient, in a unit test

cfakeiteasynetunit testing

I'm trying to figure out how to use FakeItEasy with the HttpClient, given the following code:

public Foo(string key, HttpClient httpClient = null)
{ .. }

public void DoGet()
{
    ....

    if (_httpClient == null)
    {
        _httpClient = new HttpClient();
    }

    var response = _httpClient.GetAsync("user/1);
}

public void DoPost(foo Foo)
{
    if (_httpClient == null)
    {
        _httpClient = new HttpClient();
    }

    var formData = new Dictionary<string, string>
    {
        {"Name", "Joe smith"},
        {"Age", "40"}
    };    

    var response = _httpClient.PostAsync("user", 
        new FormUrlEncodedContent(formData));
}

So i'm not sure how to use FakeItEasy, to fake out the HttpClient's GetAsync and PostAsync methods.

production code will not pass in the HttpClient, but the unit test will pass in the fake instance, made by FakeItEasy.

eg.

[Fact]
public void GivenBlah_DoGet_DoesSomething()
{
    // Arrange.
    var httpClient A.Fake<HttpClient>(); // <-- need help here.
    var foo = new Foo("aa", httpClient);

    // Act.
    foo.DoGet();

    // Assert....
}

UPDATE:

I grok that FiE (and most mocking packages) works on interfaces or virtual methods. So for this question, lets just prentend that the GetAsync and PostAsync methods are virtual … please 🙂

Best Answer

Here's my (more or less) general purpose FakeHttpMessageHandler.

public class FakeHttpMessageHandler : HttpMessageHandler
{
    private HttpResponseMessage _response;

    public static HttpMessageHandler GetHttpMessageHandler( string content, HttpStatusCode httpStatusCode )
    {
        var memStream = new MemoryStream();

        var sw = new StreamWriter( memStream );
        sw.Write( content );
        sw.Flush();
        memStream.Position = 0;

        var httpContent = new StreamContent( memStream );

        var response = new HttpResponseMessage()
        {
            StatusCode = httpStatusCode,
            Content = httpContent
        };

        var messageHandler = new FakeHttpMessageHandler( response );

        return messageHandler;
    }

    public FakeHttpMessageHandler( HttpResponseMessage response )
    {
        _response = response;
    }

    protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken )
    {
        var tcs = new TaskCompletionSource<HttpResponseMessage>();

        tcs.SetResult( _response );

        return tcs.Task;
    }
}

Here is an example of it being used from one of my tests that expects some JSON as a return value.

const string json = "{\"success\": true}";

var messageHandler = FakeHttpMessageHandler.GetHttpMessageHandler( 
    json, HttpStatusCode.BadRequest );
var httpClient = new HttpClient( messageHandler );

You would now inject httpClient into your class under test (using whatever injection mechanism you prefer) and when GetAsync is called your messageHandler will spit back the result you told it to.