Search code examples
c#unit-testingasp.net-web-apiasp.net-web-api-routing

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.


Solution

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