With Test::Unit, how can I run a bit of code befor

2019-06-26 09:10发布

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.

3条回答
霸刀☆藐视天下
2楼-- · 2019-06-26 09:54

You can just put them at the top of the class. They will get executed, and then your tests will get executed.

查看更多
Deceive 欺骗
3楼-- · 2019-06-26 09:57

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
查看更多
4楼-- · 2019-06-26 10:16

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
查看更多
登录 后发表回答