Background
Testing controller actions is pretty simple:
- Instantiate the controller
- Invoke the action
- Test the result.
However, you can't use this same pattern for testing filters applied to actions or controllers. Filters are invoked by the ASP.NET MVC framework. When you invoke an action directly on the controller, it does not execute the filters for the controller or the action.
For example, the following test case fails:
As mentioned above, to test filters you need to test two things:
- The filter is applied to you controller or action
- The filter code
Testing Filter Application
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:
Testing Filters
Testing filters is more complicated that testing controllers. We need to: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 Filters
- Mock up a filter context
- Create the filter
- Invoke the appropriate filter action
- Test the filter result
Further reading:
No comments:
Post a Comment