Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

You can unit test a class that uses HttpClient by giving that HttpClient a mock HttpMessageHandler. This way, you can capture the request and prevent it from actually going over the wire.

 

Here is an example using Moq. HttpClient depends on HttpMessageHandler’s SendAsync() method, so give SendAsync() a stub implementation and use Moq’s Callback() to capture arguments.

 

var handler = new Mock<HttpMessageHandler>();

handler.Protected()

    .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())

    .Returns(Task<HttpResponseMessage>.Factory.StartNew(() =>

    {

        return new HttpResponseMessage(HttpStatusCode.OK);

    }))

    .Callback<HttpRequestMessage, CancellationToken>((r, c) =>

    {

        Assert.AreEqual(HttpMethod.Get, r.Method);

    });

 

using (var client = new HttpClient(handler.Object))

{

    var request = new HttpRequestMessage(HttpMethod.Get, "http://www.google.com");

    var response = client.SendAsync(request).Result;

    Console.WriteLine(response.StatusCode);

}

Posted on Wednesday, November 20, 2013 4:32 PM .net , unit testing , c# , moq , httpclient | Back to top


Comments on this post: Unit tests for HttpClient using HttpMessageHandler

# re: Unit tests for HttpClient using HttpMessageHandler
Requesting Gravatar...
It's a little more efficient to return Task.FromResult(...) rather than Task.Factory.StartNew(...)
Left by Dave on Sep 17, 2014 9:00 PM

# re: Unit tests for HttpClient using HttpMessageHandler
Requesting Gravatar...
Great post. I've been looking for this exact thing. Cheers!
Left by Chris Smith on Aug 07, 2015 3:49 PM

Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net