小编som*_*one的帖子

单元测试ActionFilter - 正确设置ActionExecutingContext

在自定义中ActionFilter,我想检查将要执行的控制器操作的属性.运行一个小型测试应用程序,以下工作在asp.net开发服务器中启动应用程序时 -

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)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

一个没有SomeAttribute抛出的动作方法ArgumentException,相反,一个动作方法没有抛出SomeAttribute.到现在为止还挺好.

现在我想为ActionFilter设置一些单元测试,但是如何设置OnActionExecuting方法应该在单元测试中运行的action方法?使用以下代码找不到SomeAttribute将要执行的操作方法.测试设置正确吗?我没有在测试中正确安排一些东西吗?澄清一下,测试并不完整,但我不确定我错过了什么,以便someAttributeOnActionExecuting测试中null

    [TestMethod]
    public void Controller_With_SomeAttribute()
    {
        FakeController fakeController =
            new FakeController();

        ControllerContext controllerContext = 
            new ControllerContext(new …
Run Code Online (Sandbox Code Playgroud)

unit-testing moq action-filter asp.net-mvc-2

4
推荐指数
1
解决办法
4794
查看次数

标签 统计

action-filter ×1

asp.net-mvc-2 ×1

moq ×1

unit-testing ×1