【发布时间】:2014-07-16 20:53:54
【问题描述】:
我在测试从 Web API 内部生成 MVC 路由时遇到问题。该代码在手动点击时有效,但在测试中失败,因为 Web API 的内存实例不知道 MVC 路由,我不知道如何添加它们。
这里有一个 github 上的 example project 来说明问题,但我会在此处包含一些相关代码。
我正在使用内存中的 HTTP 服务器来托管 Web API 以进行集成测试:
private HttpConfiguration _config;
private HttpServer _server;
private HttpMessageInvoker _client;
[TestInitialize]
public void TestInitialize()
{
_config = new HttpConfiguration();
WebApiConfig.Register(_config);
_server = new HttpServer(_config);
_client = new HttpMessageInvoker(_server);
}
在我的 Web API 控制器中,我尝试通过开箱即用的默认路由(Web API 和 Mvc)返回链接:
[HttpGet]
[Route("MvcRoute")]
public string MvcRoute()
{
return Url.Link("Default", new {Controller = "Other", Action = "Index"});
}
[HttpGet]
[Route("ApiRoute")]
public string ApiRoute()
{
return Url.Link("DefaultApi", new {Controller = "Example", Id = "MvcRoute"});
}
ApiRoute 测试通过,但 MvcRoute 测试失败,并显示错误消息“在路由集合中找不到名为 'Default' 的路由。”:
[TestMethod]
public void ShouldReturnMvcRoute()
{
using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/example/mvcroute"))
{
using (var response = _client.SendAsync(request, CancellationToken.None).Result)
{
var responseContent = response.Content.ReadAsStringAsync().Result;
Assert.AreEqual("\"http://localhost/Other\"", responseContent);
}
}
}
那么我怎样才能让内存服务器知道 MVC 的路由呢?或者,如果这是一个错误的问题,我该如何在构建服务器(即没有 IIS)上运行自动化测试,以访问生成 MVC 路由链接的 Web API 路由?
【问题讨论】:
标签: asp.net-mvc-routing asp.net-mvc-5 integration-testing asp.net-web-api2 asp.net-web-api-routing