How can you unit test an Action Filter in ASP.NET Web Api?

后端 未结 6 1705
我寻月下人不归
我寻月下人不归 2020-12-22 22:43

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

6条回答
  •  天涯浪人
    2020-12-22 23:24

    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() { 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;
    }
    

    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:

    • AuthorizeAttributeTest

    • ActionFilterAttributeTest

    ActionFilterAttributeTest is the test class for ActionFilterAttribute which is an abstract class but you will get the idea.

提交回复
热议问题