11

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.

2
  • It is strange that I can't repro your issue. Everything works fine on my machine. What is the version of webapi you used? Have you provided with all your test code? I think the unit test won't run about the attribute routing part. Commented Jul 27, 2014 at 14:57
  • What is "urlHelper" in your controller action? Can you share full of it? Thanks Commented Jul 28, 2014 at 0:20

2 Answers 2

15
+100

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?

Sign up to request clarification or add additional context in comments.

1 Comment

I've rechecked everything, because you saids it worked. And it works on my machine too. Thanks!
2

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

1 Comment

In the attached post, there is a great effort in configuring the HttpConfiguration. Can this effort be saved by an axiomatic approach, namely, calling WebApiConfig.Register(testConfig) in the original project? This, however, assumes the correctness of WebapiConfig.Register. Hence the axiomatic approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.