Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
Syska Avatar asked Jan 28 '14 17:01

Syska


People also ask

How will you unit test a controller?

Unit testing controllers. Set up unit tests of controller actions to focus on the controller's behavior. A controller unit test avoids scenarios such as filters, routing, and model binding. Tests that cover the interactions among components that collectively respond to a request are handled by integration tests.

What are the three essential is related to unit testing?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

What should I test with unit tests?

Unit tests should validate all of the details, the corner cases and boundary conditions, etc. Component, integration, UI, and functional tests should be used more sparingly, to validate the behavior of the APIs or application as a whole.


1 Answers

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

like image 103
Syska Avatar answered Oct 04 '22 18:10

Syska