问题
In my test app, which uses test::unit, I need to start by pulling a bunch of data from various sources. I'd like to only do this once - the data is only read, not written, and doesn't change between tests, and the loading (and error checking for the loading), takes some time.
There are values that I DO want reset every time, and those are easy enough, but what if I want persistant accessible values? What's the best way to do this?
I'm especially interested in solutions that would let my push those assignments to some module that can be included in all my tests, since they all need access to this data.
回答1:
Why do you need it inside the test? You could define it gloabl:
gem 'test-unit'#, '>= 2.1.1' #startup
require 'test/unit'
GLOBAL_DATA = 11
class My_Tests < Test::Unit::TestCase
def test_1()
puts "Testing startup 1"
assert_equal(11, GLOBAL_DATA)
end
end
GLOBAL_DATA could be a (singleton)-class (respective an instance).
If you have only one testclass, you may use TestCase.startup:
gem 'test-unit'#, '>= 2.1.1' #startup
require 'test/unit'
class My_Tests < Test::Unit::TestCase
def self.startup
puts "Define global_data "
@@global_data = 11
end
def test_1()
puts "Testing 1"
assert_equal(11, @@global_data = 11)
end
def test_2()
puts "Testing 2"
assert_equal(11, @@global_data = 11)
end
end
回答2:
You can just put them at the top of the class. They will get executed, and then your tests will get executed.
回答3:
You could do this in the setup method:
def setup
if !defined?(@@initial_data)
# Whatever you need to do to get your initial data
@@initial_data = foo
end
@other_data = bar
end
来源:https://stackoverflow.com/questions/7729444/with-testunit-how-can-i-run-a-bit-of-code-before-all-tests-but-not-each-test