Using the HttpClientInterception to Test Methods That Use a HttpClient

Full source code available here.

In my previous post I showed a way of testing a controller that uses a HttpClient.

I had to mock the HttpMessageHandler pass that to the HttpClient and set a bunch of properties. It works well, but is a bit long winded.

I received a comment from a reader who suggested that I try the JustEat.HttpClientInterception library. It allows you to setup responses to specified requests, and pass these to a HttpClient. Then the HttpClient is passed to the controller.

Here is how the test method looks -

 1[Fact]
 2public async Task GetTest()
 3{
 4    //Arrange
 5    List<int> myList = new List<int>() {1, 2, 3, 4, 5};
 6    
 7    // setup the interceptor
 8    HttpRequestInterceptionBuilder builder = new HttpRequestInterceptionBuilder()
 9        .ForHost("localhost.something.com")
10        .ForPath("/v1/numbers")
11        .WithJsonContent(myList);
12    
13    // create the HttpClient from the builder
14    // and setup the HttpClientBaseAddress
15    HttpClient client = new HttpClientInterceptorOptions()
16        .Register(builder).CreateHttpClient("http://localhost.something.com/v1/");
17
18    ValuesController controller = new ValuesController(client);
19
20    //Act
21    IActionResult result = await controller.Get();
22
23    //Assert
24    OkObjectResult resultObject = result as OkObjectResult;
25    Assert.NotNull(resultObject);
26
27    List<int> numbers = resultObject.Value as List<int>;
28    Assert.Equal(5, numbers.Count);
29}

Briefly, here is the constructor of the values controller. It takes the HttpClient as a parameter, usually passed by dependency injection.

 1public class ValuesController : Controller
 2{
 3    readonly IAsyncPolicy<HttpResponseMessage> _httpRetryPolicy;
 4    private readonly HttpClient _httpClient;
 5
 6    public ValuesController(HttpClient httpClient)
 7    {
 8        _httpClient = httpClient;
 9    }
10	//snip..

Full source code available here.

comments powered by Disqus

Related