How to test ActionFilterAttribute - OnActionExecuted

I am trying to unit test to create a special ActionFilterAttribute. For instance:

public class ActionAuthorizationAttribute: ActionFilterAttribute { protected override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.HttpContext.Response.Redirect("SecurityException"); } } 

How can I write a unit test that will verify that any action that has this attribute will be redirected to a SecurityException.

My attempt

 [TestClass] public class TestControllerResponse { [TestMethod] public void TestPermissionAccepted() { var controller = new TestController(); var result = controller.Index() as RedirectToRouteResult; Assert.IsNotNull(result); Assert.AreEqual("SecurityException", result.RouteValues["action"]); } } protected class TestController : Controller { [ActionAuthorization] public ActionResult Index() { return RedirectToAction("UnfortunatelyIWasCalled"); } } 

Unfortunately, the test failed. The index action is redirected to "SorryIWasCalled" instead of "SecurityException".

+4
source share
1 answer

I would not become Unit Test action of controllers to check the behavior of the action filter. These are two separate issues. For example, if someone goes and changes the ActionAuthorizeAttributes OnActionExecutedMethod to return another exception, your Unit Test in the Controllers action will fail for the wrong reason. This is because you are testing an action, but your code is also testing something else in ActionFilter. Unit testing is testing the behavior of a work unit in isolation. If you really want to test ActionFilter, I would highlight the Unit Test filter separately. Regardless of whether the ActionFilter is called after your action is launched, this is a separate issue and has already been tested by the MVC framework.

+1
source

All Articles