Noel
Noel

Reputation: 2120

WebApi unit testing the urlhelper is now null

I have some unit tests that test the post in a WebApi project it was a WebApi 1.0 version, that I have upgraded to webapi 2.0, now when trying to construct the response, and add the location of the new resource the ApiController.Url returns null. Prior to upgrading these unit tests were passing. Here is the setup of the controller

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;

Here is the call that is failing . Note it is the Url object that is returning null

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

So what am I doing wrong now that I have upgrade to the latest version?

Upvotes: 4

Views: 1721

Answers (1)

Noel
Noel

Reputation: 2120

I found a answer elsewhere on Stackoverflow

In WebApi 1.0 in the last line of code in the first code sample above

Controller.Request = request;

The controller creates a UrlHelper and populates the property controller.Url. That no longer happens in Web Api 2.0. The suggestion from the other thread is to create it yourself in your unit tests. So I added the line (as suggested in the other thread).

controller.Url = new UrlHelper(request); 

Upvotes: 6

Related Questions