How to unit test ASP.NET Web API 2 Route Attributes

Posted on December 9th, 2017

Issue

What I thought was a simple search on the web turned out to be more than that.

The closets to a solution I found was from the person who first made it possible to use Attributes for routing in ASP.NET MVC 4: AttributeRouting not working with HttpConfiguration object for writing Integration tests

But what about ASP.NET Web Api 2?

HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes(); // This don't work. I guess there is needed some more plumbing to know what Controllers to search for attributes, but I'm lost here.
HttpServer server = new HttpServer(config);
using (HttpMessageInvoker client = new HttpMessageInvoker(server))
{
    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "http://localhost/api/accounts/10"))
    using(HttpResponseMessage response = client.SendAsync(request, CancellationToken.None).Result)
    {
        response.StatusCode.Should().Be(HttpStatusCode.Created);
    }
}

Solution

It turns of that I was missing a simple little line, just after the “config.MapHttpAttributes();”

config.EnsureInitialized();

So finally I got this working.

But why on earth does the HttpServer class or something else not ensure that the config have been initialized.

Why

So I was searching for a reason why this was needed and why this should actually be called.

If you decompile: System.Web.Http.GlobalConfiguration.Configure(Action<HttpConfiguration> configurationCallback)

You will get something like this:

public static void Configure(Action<HttpConfiguration> configurationCallback)
{
  if (configurationCallback == null)
    throw new ArgumentNullException("configurationCallback");
  configurationCallback(GlobalConfiguration.Configuration);
  GlobalConfiguration.Configuration.EnsureInitialized();
}

Why on earth is it done like that ... for me this has absolutely nothing to do with Ensure ... THIS needs to be called after all configuration is done.

Is can be called multiple times with no side effects.

Why ohhh why do you sometime hate us so much Microsoft. :-)