Last active
December 14, 2015 10:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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