Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit tests with attribute based routing

I have a controller with a routing attribute. This controller fails in a unit test because the route could not be found:

A route named 'Values' could not be found in the route collection

This is the controller method:

[Route("api/values", Name="ApiValues")]
[HttpGet]
public HttpResponseMessage Get()
{ 
    urlHelper.Link("ApiValues", new {});
}

This is my unit test:

var valuesController = new ValuesController()
{
    Request = new HttpRequestMessage
    {
        RequestUri = new Uri("http://localhost/api/")
    },
    Configuration = new HttpConfiguration()
};

valuesController.Get();

I also tried to add this to the unit test:

valuesController.Configuration.MapHttpAttributeRoutes();
valuesController.Configuration.EnsureInitialized();

But that didn't help anything.

like image 214
user369117 Avatar asked Jul 22 '14 08:07

user369117


2 Answers

I got the same error:

A route named 'Values' could not be found in the route collection.

But the unit test passes on my machine after I add MapHttpAttributeRoutes and EnsureInitialized:

var valuesController = new ValuesController()
{
    Request = new HttpRequestMessage { RequestUri = new Uri("http://localhost/api/") },
    Configuration = new HttpConfiguration()
};

valuesController.Configuration.MapHttpAttributeRoutes();
valuesController.Configuration.EnsureInitialized();

valuesController.Get();

Can you provide with more information to repro the issue or check whether there is any difference between our test code?

like image 68
Feng Zhao Avatar answered Sep 21 '22 05:09

Feng Zhao


Instead of calling the controller directly in the Unit tests, use Helper methods to get Controller context and Action context. This will avoid the use of

valuesController.Configuration.MapHttpAttributeRoutes();
valuesController.Configuration.EnsureInitialized();

Refer the awesome explanation by Filip W. on Testing routes in Web API 2

like image 20
Aditya Singh Avatar answered Sep 19 '22 05:09

Aditya Singh