如何测试 MVC 控制器的事件 [英] How can I test an event of a MVC controller

查看:14
本文介绍了如何测试 MVC 控制器的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试 MVC 控制器的 OnExceptionOnActionExecuted 事件.

I want to test the OnException, OnActionExecuted event of an MVC controller.

如果我像这样使用模拟:

If I use mock like this:

        var httpContext = MockRepository.GenerateMock<HttpContextBase>();
        var request = MockRepository.GenerateMock<HttpRequestBase>();

        httpContext.Expect(c => c.Request).Return(request).Repeat.AtLeastOnce();
        request.Expect(r => r.IsAuthenticated ).Return(true).Repeat.AtLeastOnce();


        var controller = new MyController() ;

        controller.ControllerContext = new ControllerContext(httpContext,
                                                             new RouteData(),
                                                             controller);

        var result = controller.Execute() as ViewResult;

…action 方法正在执行,但事件没有被调用.

…the action method is executing, but the events are not invoked.

推荐答案

这是 MVC 的关注点分离原则之一.当您对一个方法进行单元测试时,您正在测试该方法本身,而与应用于它的任何过滤器无关.(而 OnException() 和 OnActionExecuting() 实际上只是美化的过滤器.)

This is one of the separation of concerns principles of MVC. When you're unit testing a method, you're testing the method itself independent of any filters applied to it. (And OnException() and OnActionExecuting() are really just glorified filters.)

如果您想独立测试那些其他方法,您可以自由地这样做.通常你会这样做的方法是像这样调用过滤器:

If you want to test those other methods independently, you're free to do so. Normally the way you'd go about this is by calling the filters like so:

((IActionFilter)controller).OnActionExecuting(...)
((IExceptionFilter)controller).OnException(...)

您必须创建上下文对象以传递给这些方法.最后,您有三个单元测试:一个用于 OnActionExecuting(),一个用于 OnException(),另一个用于您正在测试的实际方法.这种设置的好处在于,一旦您对过滤器进行了一次单元测试,您就不必再为任何其他单元测试担心它们了.

You'll have to create context objects to pass to these methods. In the end, you have three unit tests: one for OnActionExecuting(), one for OnException(), and one for the actual method you're testing. The nice thing about this setup is that once you've unit tested the filters once, you don't have to worry about them any more for any other unit tests.

例如,如果您有 Method1()、Method2() 和 Method3(),则不需要测试每个方法 + 过滤器的组合.只需进行五个单元测试:OnActionExecuting()、OnException()、Method1()、Method2() 和 Method3().这消除了冗余测试,并且可以更轻松地跟踪代码中的潜在错误.

For example, if you have a Method1(), Method2(), and Method3(), you don't need to test each combination of method + filters. Simply have five unit tests: OnActionExecuting(), OnException(), Method1(), Method2(), and Method3(). This eliminates redundant testing and makes it easier to track down potential bugs in your code.

这篇关于如何测试 MVC 控制器的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆