Skip to content

Instantly share code, notes, and snippets.

@glennblock
Last active December 14, 2015 10:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glennblock/5074004 to your computer and use it in GitHub Desktop.
Save glennblock/5074004 to your computer and use it in GitHub Desktop.
So you don't hate yourself when you try to test a controller.
public static void ConfigureForTesting(this ApiController controller, HttpRequestMessage request, string routeName = null, HttpRoute route = null)
{
var config = new HttpConfiguration();
controller.Configuration = config;
if (routeName != null && route !=null)
config.Routes.Add(routeName, route);
else
route = config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
var controllerTypeName = controller.GetType().Name;
var controllerName = controllerTypeName.Substring(0, controllerTypeName.IndexOf("Controller")).ToLower();
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", controllerName } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.ControllerContext.ControllerDescriptor = new HttpControllerDescriptor(config, controllerName, controller.GetType());
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
controller.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment