如何在ASP.NET Web Api中testingAction Filter?

我正在寻找添加一个Action Filter到我的服务来处理添加链接数据到响应消息。 我发现我需要模拟HttpActionExecutedContext,但这是一个困难的类来模拟,你如何处理动作filtertesting?

你可以像下面那样为HttpActionExecutedContext创build一个假的:

 public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null) { HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext(); HttpActionDescriptor descriptor = actionDescriptor ?? new Mock<HttpActionDescriptor>() { CallBase = true }.Object; return new HttpActionContext(context, descriptor); } 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; } 

我只是从ASP.NET Web API源代码复制并粘贴该代码: ContextUtil类。 以下是一些关于如何testing内置filter的示例:

  • AuthorizeAttributeTest

  • ActionFilterAttributeTest

ActionFilterAttributeTestActionFilterAttributeTest的testing类,它是一个抽象类,但你会明白。

只是新的一个。

 private HttpActionContext CreateExecutingContext() { return new HttpActionContext { ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() } }; } private HttpActionExecutedContext CreateExecutedContextWithStatusCode(HttpStatusCode statusCode) { return new HttpActionExecutedContext { ActionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() } }, Response = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent("blah") } }; } 

当我试图testing一个自定义的未处理的exceptionfilter时,我遇到了同样的问题。

这个伎俩。 很多新的和很长的一行代码。

 var httpActionExecutedContext = new HttpActionExecutedContext( new HttpActionContext( new HttpControllerContext( new HttpConfiguration(), Substitute.For<IHttpRouteData>(), new HttpRequestMessage()), Substitute.For<HttpActionDescriptor>()), null); 

NSubstiute被使用,但是你所select的处理抽象基类的任何模拟框架都可以。

希望这可以帮助

我也一直把头撞在一堵砖墙上。 我试过contextUtil但不断得到一个空引用exception。 我发现如何在这个post中调用actionFilter注意事项当使用filter的Mock实例时,actionFilter没有被调用,我不得不使用真实的对象。 HTH

特别:

 var httpActionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Request = requestMessage } }; //call filter var filter = new FooFilter(); filter.OnActionExecuting(httpActionContext);