Welcome to My Nerditorium

Thoughts on coding, gaming, and nerdy media.

Unit Testing a WebAPI DelegatingHandler With a DependencyScope via an HttpMessageInvoker

I’ve been working with ASP.NET WebAPI on a day-to-day basis for about seven months now, and I have to say that I really appreciate how testable it is. Although the self-hosting capability of WebAPI seems like an obvious way to facilitate a test-first workflow, I personally favor two other methodologies.

Testing with dependencies is straightforward with in-memory hosting because it is obvious that you can provide the HttpServer instance with an HttpConfiguration object containing an IDependencyResolver. However, when it comes to testing handlers via an HttpMessageInvoker, it is not entirely obvious or discoverable as to how you can wire up an HttpConfiguration (and therefore an IDependencyResolver).

Here is the secret sauce: you can add an HttpConfiguration to a request object via a “stringly typed” “MS_HttpConfiguration” property on the HttpRequestMessage object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[TestMethod]
public void SomeHandlerTest()
{
   // ... other test setup
   // ... set up handlerUnderTest including inner test handler

   request = new HttpRequestMessage(HttpMethod.Get, serverUrl + "/resource/1?someParam=foo");
   request.Properties["MS_HttpConfiguration"] = MethodThatReturnsAnHttpConfigWithDepResolver();

   invoker = new HttpMessageInvoker(handlerUnderTest);

   var response = invoker.SendAsync(request, new CancellationToken())
                                  .Result;
   // ... asserts
}

Comments