Unit Testing ASP.NET Web API

This is one of those things that I encounter now and then and always forgot how to do. I have to search the web and most of the results are for ASP.NET MVC, not for Web API. This time I found the solution on http://www.peterprovost.org/blog/2012/06/16/unit-testing-asp-dot-net-web-api/ and decided to document it.

var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Get, "http://host/api/my");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "my" } });
var controller = new MyController();
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

I’m not sure you need the route stuff, but the config is needed.

Another variant of this is constructing an HttpRequestMessage that be passed to the UrlHelpeconstructor:

var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Get, "http://host/2.2/api/se/15/controller");
var route = config.Routes.MapHttpRoute(
            name: RoutesConstants.IncludeResourceSpecificOptionsRouteName,
            routeTemplate: "api/{country}/{deviceVersion}/{controller}/{id}",
            defaults:
                new
                {
                    id = RouteParameter.Optional,
                    country = RouteParameter.Optional,
                    deviceVersion = RouteParameter.Optional
                });
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
var urlHelper = new UrlHelper(request);

Another related problem is if the controller accesses HttpContext.Current.Request. That you can just assign:

HttpContext.Current = new HttpContext(new HttpRequest(null, "http://someurl", null), new HttpResponse(new StringWriter()));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s