我如何单元测试ASP.NET MVC的ActionFilter? [英] How do I unit test an ActionFilter in ASP.NET MVC?

查看:118
本文介绍了我如何单元测试ASP.NET MVC的ActionFilter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 ActionFilter 在我的控制器类。在 OnActionExecuting 方法被调用,当控制器的动作被称为Web应用程序。

There is an ActionFilter on my controller-class. The OnActionExecuting method gets called, when an action of the controller is called in a web application.

现在我称之为动作中的UnitTest:

Now I call the Action in a UnitTest:

    NiceController niceController = new NiceController();
    ActionResult result = niceController.WhateverAction();

有没有办法有ActionFilter叫什么?

Is there a way to have the ActionFilter called?

推荐答案

为了有自动调用了ActionFilter,你将需要运行控制器操作调用。这是可能的,但它意味着MVC框架会尝试执行的结果。这意味着,你将不得不使用嘲笑存根出结果的执行。再次,这是可能的,但它意味着你的单元测试正变得比实际code的嘲弄。这可能是比较正确的,只是直接测试过滤器。毕竟,事实上,OnActionExecuting被称为是框架的一个特点,你不需要单元测试框架本身。

In order to have the ActionFilter called automatically, you are going to need to run the controller action invoker. This is possible, but it means that the MVC framework will try and execute the result. This means that you would have to use mocks to stub out the execution of the result. Again, that is possible, but it means that your unit test is becoming more mocks than actual code. It may be more correct to just test the filter directly. After all, the fact that OnActionExecuting is called is a feature of the framework, and you don't need to unit test the framework itself.

不过,我认为,你真的要说的是,你要测试WhateverAction,并且除非ActionFilter已经执行该操作无法正常工作。

But I think that what you're really saying is that you want to test WhateverAction, and that action cannot work unless the ActionFilter has executed.

首先,我会问这个设计的问题。 这是正确的吗这可能是。它是合理的,例如,与授权属性的操作可能presume它执行时,有在用户已登录。当然,动作要对此进行测试,但presumption是安全的。在另一方面,行动可能不需要过滤器,以执行特定动作的初始化。所以,你应该问的问题,但答案,他们的情况是,设计是正确的。

First, I would ask questions about this design. Is this correct? It might be. It is reasonable, for example, that an action with the Authorize attribute could presume that when it executes there is a logged in user. Of course, the action should test this, but the presumption is safe. On the other hand, actions should probably not require filters to do action-specific initialization. So you should ask the question, but the answer they well be that the design is correct.

在这种情况下,一个单元测试的最好的决定可能是在单元测试手动执行的过滤器,并的写一个独立的单元测试,证明该动作装饰有正​​确的属性。

In this case, the best decision for a unit test might be to manually execute the filter in the unit test, and to write a separate unit test which proves that the action is decorated with the correct attribute.

这篇关于我如何单元测试ASP.NET MVC的ActionFilter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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