21

在整个测试套件(不仅仅是一个测试类)中的每个方法之前运行设置的最佳方法是什么?

Rspec 允许您在块之前和之后定义全局。在不涉及将模块混合到每个测试类中的 Test::Unit 中是否有一种干净的可比方法?

4

2 回答 2

24

假设您正在使用 Rails。只需在您的test/test_helper.rb文件中添加以下内容。

class ActiveSupport::TestCase
  setup :global_setup

  def global_setup
    #stuff to run before _every_ test.
  end
end

在 Rails 3.0.9 上测试。

于 2011-08-16T11:10:18.830 回答
7

您可以修补Test::Unit::TestCase并定义一个setup方法:

class Test::Unit::TestCase
  def setup
    puts 'in setup'
  end
end

默认情况下,您的子类只会使用它:

class FooTest < Test::Unit::TestCase
  def test_truth
    assert true
  end
end

class BarTest < Test::Unit::TestCase
  def test_truth
    assert true
  end
end

如果测试用例需要有自己的设置,您需要先调用super以确保全局设置运行:

class BazTest < Test::Unit::TestCase
  def setup
    super
    puts 'custom setup'
  end

  def test_truth
    assert true
  end
end

是否真的需要进行全局设置,或者定义一个辅助方法Test::Unit::TestCase并在需要它的测试中调用它会有所帮助?辅助方法方法对我的项目很有帮助——设置状态和意图在每个单独的测试中都更加清晰,我不需要四处寻找一些“隐藏”的设置方法。很多时候,全局设置是一种代码味道,表明您需要重新考虑部分设计,但 YMMV。

更新

由于您使用的是 ActiveSupport,因此super每次setup在测试用例中定义方法时都不需要调用此功能。我不知道它有多大价值,因为它需要调用不同的方法,并且任何开发人员都可以setup在测试用例中定义自己的方法,这将使该更改无效。这里是:

require 'rubygems'
require 'test/unit'
require 'active_support'
require 'active_support/test_case'

class ActiveSupport::TestCase

  def setup_with_global
    puts 'In Global setup'
    setup_without_global
  end

  alias_method_chain :setup, :global

end

class FooTest < ActiveSupport::TestCase

  def setup_without_global
    puts 'In Local setup'
  end

  def test_truth
    assert true
  end

end
于 2009-11-15T11:05:09.070 回答