C# 基于属性路由的单元测试

C# 基于属性路由的单元测试,c#,unit-testing,asp.net-web-api,asp.net-web-api-routing,C#,Unit Testing,Asp.net Web Api,Asp.net Web Api Routing,我有一个具有路由属性的控制器。此控制器在单元测试中失败,因为找不到路由: 在路由集合中找不到名为“Values”的路由 这是控制器方法: [Route("api/values", Name="ApiValues")] [HttpGet] public HttpResponseMessage Get() { urlHelper.Link("ApiValues", new {}); } 这是我的单元测试: var valuesController = new ValuesControll

我有一个具有路由属性的控制器。此控制器在单元测试中失败,因为找不到路由:

在路由集合中找不到名为“Values”的路由

这是控制器方法:

[Route("api/values", Name="ApiValues")]
[HttpGet]
public HttpResponseMessage Get()
{ 
    urlHelper.Link("ApiValues", new {});
}
这是我的单元测试:

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

valuesController.Get();
valuesController.Configuration.MapHttpAttributeRoutes();
valuesController.Configuration.EnsureInitialized();
我还尝试将此添加到单元测试中:

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

valuesController.Get();
valuesController.Configuration.MapHttpAttributeRoutes();
valuesController.Configuration.EnsureInitialized();
但是这没有任何帮助。

我得到了同样的错误:

A route named 'Values' could not be found in the route collection.
但是在我添加
MapHttpAttribute路由
确保重新初始化后,单元测试在我的机器上通过了:

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

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

valuesController.Get();

您可以提供更多信息来重新处理问题或检查我们的测试代码之间是否有任何差异吗?

不要在单元测试中直接调用控制器,而是使用助手方法获取
控制器上下文
操作上下文
。这将避免使用

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

请参考菲利普·W.在

上的精彩解释,奇怪的是我不能重新解释你的问题。我的机器一切正常。您使用的webapi版本是什么?您是否提供了所有的测试代码?我认为单元测试不会针对属性路由部分运行。控制器操作中的“urlHelper”是什么?你能分享全部吗?谢谢,我已经检查了所有的东西,因为你说它有效。它在我的机器上也能工作。谢谢