If I decorate a controller action with a custom ActionMethodSelectorAttribute, the attribute is evaluated during standard use and I can break in the attribute's body during a debug session. However, the attribute is not assessed / evaluated when the controller action is called during a unit test, nor will it break during debug. Why is this? Surely behaviour should be identical whether running normally or under test?
开发者_运维技巧Thanks
It's the ASP.NET MVC framework that's responsible for running action filters. Internally, it's using reflection to inspect the controller and action method, and if the method or controller are decorated with any ActionFilter attributes, it'll run those filters at the appropriate point in the request lifecycle.
For unit testing, you'll want to unit-test your action filters separately - inject a mocked ActionExecutedContext (or whichever context you're filtering) into the filter method directly, and verify that the route / result / viewdata are modified as required.
If you're really committed to 100% test coverage, you can also implement unit tests that'll use reflection to verify that you've got the required action filter attributes decorating the appropriate controller methods.
Don't worry about tests to make sure the action filters are fired - those tests are part of the ASP.NET MVC source code and last time I looked, they were all green.
The attribute will be invoked by some part of the MVC framework by reflecting over the controller and invoking the required method(s). If your tests look something like:
Controller testController = new YourController(dependecies);
ActionResult result = testController.Action();
//assert on result
Then nothing will be processing the attribute, so your breakpoint will not be hit.
精彩评论