ApiControllers Unit Testing with RouteAttribute Attribute

What I thought was a simple Internet search turned out to be more than that.

Closest to the solution was that at first it allowed the use of attributes for routing: AttributeRouting does not work with the 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 enter my controller so that it reads the attributes on the controller and sets the routes so that I can really do some testing?

+8
c # unit-testing asp.net-mvc-routing asp.net-web-api2
source share
1 answer

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

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

Basically, this starts the configuration initialization for config.MapHttpAttributeRoutes() . I think I would think that 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

+16
source share

All Articles