Here is a working example from 2018 (.NET Framework 4.5.1). It uses an ExceptionFilterAttribute, but it should be similar for other FilterAttributes.
[Test] public void MyTest() { var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.google.com")); var response = new HttpResponseMessage();
Then just copy the ContextUtil class into your test project. @Thomasb's comment on @tugberk's answer suggests that the latest code is on Codeplex . While this comment was in 2014, so there may be even later code, the 2014 code worked for me (in January 2018), while the source related code did not work. I copied a later version below for convenience. Just put this in a new file.
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; } }
Seafish Jan 18 '18 at 2:36 2018-01-18 02:36
source share