Test::Unit 中的全局设置和拆卸块
在整个测试套件(不仅仅是一个测试类)中的每个方法之前运行设置的最佳方法是什么?
Rspec 允许您定义全局的 before 和 after 块。在 Test::Unit 中是否有一种干净的可比较的方法来执行此操作,而不涉及将模块混合到每个测试类中?
What's the best way to have a setup run before every method in an entire test suite (not just one test class)?
Rspec allows you to define global before and after blocks. Is there a clean comparable way to do this in Test::Unit that doesn't involve mixing a module into each test class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您正在使用 Rails。只需在您的
test/test_helper.rb
文件中添加以下内容即可。在 Rails 3.0.9 上测试。
Assuming you're using Rails. Just add following in your
test/test_helper.rb
file.Tested on Rails 3.0.9.
您可以只修补
Test::Unit::TestCase
并定义一个setup
方法:并且您的子类默认情况下将使用此方法:
如果测试用例需要拥有自己的设置时,您需要首先调用
super
以确保全局设置运行:是否确实需要执行全局设置,或者在
上定义一个辅助方法会有所帮助吗? >Test::Unit::TestCase
并在需要它的测试中调用它?我发现辅助方法方法对我的项目有益 - 每个单独的测试中的设置状态和意图都更加清晰,我不需要四处寻找一些“隐藏”的设置方法。很多时候,全局设置是一种代码味道,表明您需要重新考虑部分设计,但是 YMMV。更新
由于您使用的是 ActiveSupport,因此这是第一次尝试,每次定义
设置
时都不需要调用super
测试用例中的方法。我不知道它有多有价值,因为它需要调用不同的方法,并且任何开发人员都可以在测试用例中定义自己的setup
方法,这将使此更改无效。这里是:You could just patch
Test::Unit::TestCase
and define asetup
method:And your subclasses would just use this by default:
If a test case needed to have its own setup, you would need to call
super
first to ensure that the global setup runs:Is having a global setup really something you need to do, or would it be helpful to have a helper method defined on
Test::Unit::TestCase
and call that in the tests that need it? The helper method approach is something that I find beneficial on my projects – the setup state and intention is clearer in each individual test and I don't need to jump around to find some "hidden" setup method. Quite often, a global setup is a code smell indicating that you need to rethink part of your design, but YMMV.Update
Since you're using ActiveSupport, here's a first stab at something that won't require a call to
super
each time you define asetup
method in your test case. I don't know how valuable it is, since it requires a call to a different method and any developer can just define their ownsetup
method in the test case that will invalidate this change. Here it is: