在自定義ActionFilter
中,我想檢查將要執行的控制器操作的屬性。通過一個小的測試應用程序中運行,啓動在asp.net開發應用程序時,以下工作服務器 -單元測試ActionFilter - 正確設置ActionExecutingContext
public class CustomActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var someAttribute = filterContext.ActionDescriptor
.GetCustomAttributes(typeof(SomeAttribute), false)
.Cast<SomeAttribute>()
.SingleOrDefault();
if (someAttribute == null)
{
throw new ArgumentException();
}
// do something here
}
public override void OnActionExecuted(ActionExecutingContext filterContext)
{
// ...
}
}
沒有SomeAttribute
的行動方法拋出ArgumentException
,相反,與SomeAttribute
操作方法沒有。到現在爲止還挺好。
現在我想爲ActionFilter設置一些單元測試,但是如何設置OnActionExecuting
方法應該在單元測試中運行的操作方法?使用以下代碼沒有找到要執行的操作方法的SomeAttribute
。測試設置是否正確?我有沒有在測試中正確安排一些內容?爲了澄清,該測試是不完整的,但我不知道我在OnActionExecuting
在測試錯過這樣someAttribute
是null
[TestMethod]
public void Controller_With_SomeAttribute()
{
FakeController fakeController =
new FakeController();
ControllerContext controllerContext =
new ControllerContext(new Mock<HttpContextBase>().Object,
new RouteData(),
fakeController);
var actionDescriptor = new Mock<ActionDescriptor>();
actionDescriptor.SetupGet(x => x.ActionName).Returns("Action_With_SomeAttribute");
ActionExecutingContext actionExecutingContext =
new ActionExecutingContext(controllerContext,
actionDescriptor.Object,
new RouteValueDictionary());
CustomActionFilterAttribute customActionFilterAttribute = new CustomActionFilterAttribute();
customActionFilterAttribute.OnActionExecuting(actionExecutingContext);
}
private class FakeController : Controller
{
[SomeAttribute]
ActionResult Action_With_SomeAttribute()
{
return View();
}
}