【问题标题】:Unit tests with attribute based routing使用基于属性的路由进行单元测试
【发布时间】:2014-09-13 00:06:50
【问题描述】:

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

在路由集合中找不到名为“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();

但这没有任何帮助。

【问题讨论】:

  • 奇怪的是我无法重现您的问题。在我的机器上一切正常。你用的webapi是什么版本的?您是否提供了所有测试代码?我认为单元测试不会针对属性路由部分进行。
  • 控制器动作中的“urlHelper”是什么?能完整分享一下吗?谢谢

标签: c# unit-testing asp.net-web-api asp.net-web-api-routing


【解决方案1】:

我遇到了同样的错误:

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

但是在我添加MapHttpAttributeRoutesEnsureInitialized 之后,单元测试在我的机器上通过了:

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

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

valuesController.Get();

您能否提供更多信息来重现问题或检查我们的测试代码之间是否有任何差异?

【讨论】:

  • 我已经重新检查了所有内容,因为您说它有效。它也适用于我的机器。谢谢!
【解决方案2】:

不要在单元测试中直接调用控制器,而是使用 Helper 方法获取 Controller contextAction context。这将避免使用

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

参考 Filip W. 在Testing routes in Web API 2 上的精彩解释

【讨论】:

  • 在附加的帖子中,在配置 HttpConfiguration 方面付出了很大的努力。是否可以通过公理化的方法来节省这项工作,即在原始项目中调用 WebApiConfig.Register(testConfig) ?但是,这假定 WebapiConfig.Register 的正确性。因此公理化方法
猜你喜欢
  • 1970-01-01
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多