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?
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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With