你单位如何测试在ASP.NET网页API的Action过滤器? [英] How can you unit test an Action Filter in ASP.NET Web Api?
问题描述
我一直在寻找一个行为过滤器添加到我的服务来处理增加链路数据的响应消息。我发现,我需要模拟HttpActionExecutedContext但它是一个困难的类嘲笑,你是如何处理的行为过滤器测试?
I was looking to add an Action Filter to my service to handle adding link data to the response message. I have found that I need to mock HttpActionExecutedContext but it's a difficult class to mock, how are you dealing with Action Filter testing?
推荐答案
您可以为 HttpActionExecutedContext
创建一个假如下:
You can create a fake for HttpActionExecutedContext
as below:
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源$ C code $ C:<一href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/changeset/view/98d041ae352f#test/System.Web.Http.Test/Util/ContextUtil.cs\">ContextUtil类。这里是他们测试了怎样一些内置的过滤器的几个例子:
I just copied and pasted that code from the ASP.NET Web API source code: ContextUtil class. Here is a few examples on how they tested some built in filters:
-
<一个href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/changeset/view/98d041ae352f#test/System.Web.Http.Test/AuthorizeAttributeTest.cs\">AuthorizeAttributeTest
<一个href=\"http://aspnetwebstack.$c$cplex.com/SourceControl/changeset/view/98d041ae352f#test/System.Web.Http.Test/Filters/ActionFilterAttributeTest.cs\">ActionFilterAttributeTest
ActionFilterAttributeTest
是 ActionFilterAttribute
测试类,它是一个抽象类,但你会得到的想法。
ActionFilterAttributeTest
is the test class for ActionFilterAttribute
which is an abstract class but you will get the idea.
这篇关于你单位如何测试在ASP.NET网页API的Action过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!