Syska
Syska

Reputation: 1149

Unit testing ApiControllers with RouteAttribute

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

The closest to a solution was the one that first made it possible to use Attributes for routing: AttributeRouting not working with HttpConfiguration object for writing Integration tests

But what about ASP.NET Web Api 2?

My unit test

HttpConfiguration config = new HttpConfiguration();
// config.MapHttpAttributeRoutes(); // This doesn'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);
    }
}

How can I inject my controller so it reads attributes on the Controller and set the routes so I can actually do some testing?

Upvotes: 10

Views: 3820

Answers (1)

Syska
Syska

Reputation: 1149

This is just ridiculous... I got it working using this:

config.MapHttpAttributeRoutes();
config.EnsureInitialized();

So basically, this runs the init of the configuration for the config.MapHttpAttributeRoutes(). I guess, I would have thought this was done automatically.

But now it works and I'm happy.

For more information on this issue see: http://ifyoudo.net/post/2014/01/28/How-to-unit-test-ASPNET-Web-API-2-Route-Attributes.aspx

Upvotes: 16

Related Questions