测试urlhelper的WebApi单元现在为null

Noe*_*oel 4 unit-testing asp.net-web-api

我有一些单元测试在WebApi项目中测试帖子它是WebApi 1.0版本,我已经升级到webapi 2.0,现在在尝试构建响应时,并添加新资源的位置ApiController.Url返回null .在升级之前,这些单元测试正在通过.这是控制器的设置

var config = new HttpConfiguration();
SetDependencyResolver(config, type);

var request = new HttpRequestMessage(method, url);
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData =
    new HttpRouteData(
        route,
        new HttpRouteValueDictionary { { "controller", controllerName } });

request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;

controller.Configuration = config;
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
Run Code Online (Sandbox Code Playgroud)

这是失败的电话.请注意,返回null的Url对象

response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = claimsCommand.Id }));
Run Code Online (Sandbox Code Playgroud)

那我现在做错了什么我升级到了最新版本?

Noe*_*oel 6

我在Stackoverflow的其他地方找到了答案

在上面第一个代码示例的最后一行代码中的WebApi 1.0中

Controller.Request = request;
Run Code Online (Sandbox Code Playgroud)

控制器创建UrlHelper并填充属性controller.Url.在Web Api 2.0中不再发生这种情况.另一个主题的建议是在你的单元测试中自己创建它.所以我添加了一行(如另一个帖子中所示).

controller.Url = new UrlHelper(request); 
Run Code Online (Sandbox Code Playgroud)