11

我已经将我的 web api 项目升级到最新版本,使用 MVC 5 应用程序运行正常,但是这行代码在我的单元测试中不再工作:

string uri = this.Url.Link("DefaultApi", new { id = savedOrganization.Id });

控制器的 Url 属性现在为空。这就是我配置模拟控制器的方式:

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 之前,它运行良好。

当我调试测试时,它显示 Url 属性现在为空 在此处输入图像描述

4

1 回答 1

14

看起来在 MVC 5 中 Url 属性是以不同的方式创建的。我在测试中引入了这一行,现在 Url 属性恢复正常

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;
}
于 2013-10-29T13:38:44.813 回答