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.
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?
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
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