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

Aaron Fischer picture Aaron Fischer · Aug 7, 2012 · Viewed 28.8k times · Source

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?

Answer

tugberk picture tugberk · Aug 7, 2012

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;
}

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:

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