单元测试与不工作的ASP.NET MVC的Web 5 API数据路由 [英] Unit Test with route data not working on ASP.NET MVC 5 Web API
问题描述
我已经升级我的Web API项目到最新版本,使用MVC 5
该应用程序运行正常,但此行code是不是在我的单元测试工作了:
I have upgraded my web api project to the latest version, using MVC 5 The application runs properly but this line of code is not working anymore on my unit tests:
string uri = this.Url.Link("DefaultApi", new { id = savedOrganization.Id });
控制器的URL属性现在空。
这是我如何配置模拟控制器:
The Url property of the controller is now null. This is how I configure the mock controller:
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://xxx/api/organization");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary {{"controller", "organization"}});
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
升级到MVC 5之前,它是工作的罚款。
Before upgrading to MVC 5 it was working fine.
当我调试测试表明Url属性现在是空
When I debug the test it shows that the Url property is now null
推荐答案
它看起来像在MVC 5以不同的方式创建Url属性。
我已经介绍了在我的测试中这行,现在的URL属性恢复正常。
It looks like in MVC 5 the Url property is created in a different way. I have introduced this line in my tests and now the Url property is back to normal
private static void SetupControllerForTests(ApiController controller)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://api.clientele-itsm.com/api/organization");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary
{
{"id", Guid.Empty},
{"controller", "organization"}
});
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
UrlHelper urlHelper = new UrlHelper(request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
/// inject a fake helper
controller.Url = urlHelper;
}
这篇关于单元测试与不工作的ASP.NET MVC的Web 5 API数据路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!