這就是它應該如何工作!
每個測試應該與其餘的完全隔離,因此setup
和tear_down
方法對每個測試用例都執行一次。在有些情況下,然而,當你可能需要在執行流程的控制。然後,您可以將測試用例組合成套件。
你的情況,你可以寫類似以下內容:
require 'test/unit'
require 'test/unit/ui/console/testrunner'
class TestDecorator < Test::Unit::TestSuite
def initialize(test_case_class)
super
self << test_case_class.suite
end
def run(result, &progress_block)
setup_suite
begin
super(result, &progress_block)
ensure
tear_down_suite
end
end
end
class MyTestCase < Test::Unit::TestCase
def test_1
puts "test_1"
assert_equal(1, 1)
end
def test_2
puts "test_2"
assert_equal(2, 2)
end
end
class MySuite < TestDecorator
def setup_suite
puts "setup_suite"
end
def tear_down_suite
puts "tear_down_suite"
end
end
Test::Unit::UI::Console::TestRunner.run(MySuite.new(MyTestCase))
的TestDecorator
定義了一個特殊套件,它提供了一個setup
和tear_down
方法,只有前和測試 - 集的運行後,運行一次它包含的案例。
這樣做的缺點是,你需要告訴測試::單位如何運行的單元測試。倘若您的單位包含了很多的測試用例,你需要的只是其中的一個裝飾,你需要這樣的事:
require 'test/unit'
require 'test/unit/ui/console/testrunner'
class TestDecorator < Test::Unit::TestSuite
def initialize(test_case_class)
super
self << test_case_class.suite
end
def run(result, &progress_block)
setup_suite
begin
super(result, &progress_block)
ensure
tear_down_suite
end
end
end
class MyTestCase < Test::Unit::TestCase
def test_1
puts "test_1"
assert_equal(1, 1)
end
def test_2
puts "test_2"
assert_equal(2, 2)
end
end
class MySuite < TestDecorator
def setup_suite
puts "setup_suite"
end
def tear_down_suite
puts "tear_down_suite"
end
end
class AnotherTestCase < Test::Unit::TestCase
def test_a
puts "test_a"
assert_equal("a", "a")
end
end
class Tests
def self.suite
suite = Test::Unit::TestSuite.new
suite << MySuite.new(MyTestCase)
suite << AnotherTestCase.suite
suite
end
end
Test::Unit::UI::Console::TestRunner.run(Tests.suite)
的文檔提供了有關如何套房工作一個很好的解釋。
兩種測試方法具有相同的名稱會導致沒有運行的第一個方法。你可以在第一次測試中放入一個失敗,測試仍然會通過。剪切和粘貼編程的一個副作用。 – 2009-02-18 01:00:19
是的,而且很簡單。這最終在TestUnit中實現。看我的帖子waaaay在這個頁面。 – jpgeek 2012-09-25 14:59:20