Created
May 30, 2014 16:43
-
-
Save juristr/9ce8baf5c04b2a56e228 to your computer and use it in GitHub Desktop.
Helper class for testing WebApi action filters
This file contains hidden or 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
internal static class ContextUtil | |
{ | |
public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null) | |
{ | |
HttpConfiguration config = configuration ?? new HttpConfiguration(); | |
IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute()); | |
HttpRequestMessage req = request ?? new HttpRequestMessage(); | |
req.SetConfiguration(config); | |
req.SetRouteData(route); | |
HttpControllerContext context = new HttpControllerContext(config, route, req); | |
if (instance != null) | |
{ | |
context.Controller = instance; | |
} | |
context.ControllerDescriptor = CreateControllerDescriptor(config); | |
return context; | |
} | |
public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null) | |
{ | |
HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext(); | |
HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor(); | |
descriptor.ControllerDescriptor = context.ControllerDescriptor; | |
return new HttpActionContext(context, descriptor); | |
} | |
public static HttpActionContext GetHttpActionContext(HttpRequestMessage request) | |
{ | |
HttpActionContext actionContext = CreateActionContext(); | |
actionContext.ControllerContext.Request = request; | |
return actionContext; | |
} | |
public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response) | |
{ | |
HttpActionContext actionContext = CreateActionContext(); | |
actionContext.ControllerContext.Request = request; | |
HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext(actionContext, null) { Response = response }; | |
return actionExecutedContext; | |
} | |
public static HttpControllerDescriptor CreateControllerDescriptor(HttpConfiguration config = null) | |
{ | |
if (config == null) | |
{ | |
config = new HttpConfiguration(); | |
} | |
return new HttpControllerDescriptor() { Configuration = config, ControllerName = "FooController" }; | |
} | |
public static HttpActionDescriptor CreateActionDescriptor() | |
{ | |
var mock = new Mock<HttpActionDescriptor>() { CallBase = true }; | |
mock.SetupGet(d => d.ActionName).Returns("Bar"); | |
return mock.Object; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment