2011-10-11 49 views
4

在我使用test :: unit的測試應用程序中,我需要從各種來源提取大量數據。我只想這樣做 - 數據只能讀取,不能寫入,並且在測試之間不會改變,加載(以及加載的錯誤檢查)需要一些時間。使用Test :: Unit,我如何在所有測試(但不是每個測試)之前運行一段代碼?

有些值我每次都想重置,而且這些值很容易,但是如果我想要持久的可訪問值,該怎麼辦?什麼是最好的方法來做到這一點?

我特別感興趣的解決方案,可以讓我將這些分配推送到可以包含在我的所有測試中的某個模塊,因爲他們都需要訪問這些數據。

+0

非常類似的問題,除了OP希望一個測試套件之前運行一些代碼,不是所有的測試套件之前: http://stackoverflow.com/questions/255969/in-rubys-testunittestcase-how-do-i-override-the-initialize-method –

回答

3

爲什麼你需要它的測試裏面?你可以定義它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可能是一個(單身)類(相應的實例)。

如果你只有一個TestClass中,你可以使用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 
1

您可以將它們放在課程的頂部。他們會被執行,然後你的測試會被執行。

1

你可以在設置方法做到這一點:

def setup 
    if !defined?(@@initial_data) 
     # Whatever you need to do to get your initial data 
     @@initial_data = foo 
    end 
    @other_data = bar 
    end 
相關問題