Testing controllers in ASP.NET MVC is straight forward. However, testing action filters applied to controllers or actions requires jumping through a few hoops. Since filters are applied by the framework, calling the action directly means no filters are executed. Thus, you write two tests: one for the filter and one that the controller is decorated with the filter.
Background
Testing controller actions is pretty simple:
- Instantiate the controller
- Invoke the action
- Test the result.
For instance:
As mentioned above, to test filters you need to test two things:
- The filter is applied to you controller or action
- The filter code
Using reflection, you can get get all the filters applied to an action or controller. The following snippet shows how you could test that a filter is applied to an action.

This code:
- Gets the action method from the controller
- Finds an attribute for the filter
- Checks that the method has a filter
Testing that controllers have filters applied is similar. See the download at the end of this post for sample code.
Testing Filters
Testing filters is more complicated that testing controllers. We need to:
- Mock up a filter context
- Create the filter
- Invoke the appropriate filter action
- Test the filter result
The following, using Moq, shows how you can perform these steps in a test: