[英]How to test ActionFilterAttribute - OnActionExecuted
I am trying to unit test a custom ActionFilterAttribute. 我正在尝试单元测试自定义ActionFilterAttribute。 For example: 例如:
public class ActionAuthorizationAttribute: ActionFilterAttribute
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.Redirect("SecurityException");
}
}
How can I write a unit test that would test that any action that would have this attribute would redirect to SecurityException. 如何编写单元测试来测试任何具有此属性的操作将重定向到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 fails. 不幸的是,测试失败了。 The index action redirects to "UnfortunatelyIWasCalled" instead of "SecurityException". 索引操作重定向到“WonderIWasCalled”而不是“SecurityException”。
I would not Unit Test the Controller's Action to test the behaviour of an Action Filter. 我不会单元测试Controller的Action来测试Action Filter的行为。 They are two separate concerns. 它们是两个不同的问题。 For example, if someone goes and changes the ActionAuthorizeAttribute's OnActionExecutedMethod to return a different exception, your Unit Test on the Controller's Action going to fail for the wrong reason. 例如,如果某人去并更改ActionAuthorizeAttribute的OnActionExecutedMethod以返回不同的异常,则Controller的Action上的Unit Test将因错误的原因而失败。 This is because, you are testing the Action, but your code also testing something else in within an ActionFilter. 这是因为,您正在测试Action,但您的代码还在ActionFilter中测试其他内容。 Unit Testing is all about verifying the behaviour of a Unit of work in isolation. 单元测试就是孤立地验证工作单元的行为。 If you really want to test the ActionFilter, I would Unit Test the filter separately. 如果你真的想测试ActionFilter,我会单独测试过滤器。 Whether the ActionFilter get called after your Action gets executed is a separate concern and that has been already tested by the MVC framework. 在Action执行后是否调用ActionFilter是一个单独的问题,并且已经过MVC框架的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.