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

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

问题描述

我想测试一个MVC控制器的 onException的 OnActionExecuted 事件。

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

如果我用模拟这样的:

        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;

...操作方法执行,但事件不被调用。

…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.

例如,如果你有一个方法1()方法2()和Method3(),你并不需要测试方法+过滤器的每个组合。只是有五个单元测试:OnActionExecuting(),onException的(),方法1(),方法2(),和Method3()。这消除了多余的测试并使其更容易跟踪潜在的错误在code。

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天全站免登陆