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?
In order to make it easier for you to implement a custom action filter, the ASP.NET MVC framework includes a base ActionFilterAttribute class. This class implements both the IActionFilter and IResultFilter interfaces and inherits from the Filter class.
You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.
In this article, we will learn how to write unit test case for Web API controller. Following is a very common pattern in Unit Testing. In the first step, we will have to create test data for testing, using a mock or stub object. This approach will minimize the number of dependencies.
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:
AuthorizeAttributeTest
ActionFilterAttributeTest
ActionFilterAttributeTest
is the test class for ActionFilterAttribute
which is an abstract class but you will get the idea.
Just new one up.
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") } }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With