2009-11-18 159 views
2

我嘗試使用Test :: Unit測試模塊時遇到問題。我以前做的是:測試模塊與測試::單元

my_module.rb:

class MyModule 
    def my_func 
    5 # return some value 
    end 
end 

test_my_module.rb:

require 'test/unit' 
require 'my_module' 

class TestMyModule < Unit::Test::TestCase 
    include MyModule 

    def test_my_func 
    assert_equal(5, my_func) # test the output value given the input params 
    end 
end 

現在的問題是,如果my_module聲明的初始化方法,它被包含在測試類,這將導致自Test :: Unit之後的一堆問題似乎會覆蓋/生成初始化方法。所以我想知道測試模塊的最佳方法是什麼?

我也想知道我的模塊在這一點上應該成爲一個類,因爲初始化方法是爲了初始化某些事情而做的。意見?

在此先感謝!

+0

如果'MyModule'是一個類,那麼'include MyModule'將引發一個'TypeError'。你是否遇到類和模塊混淆? – 2010-09-30 05:34:14

回答

3

是的,你的初始化肯定會建議你去上課。 Ruby中的模塊通常感覺就像是其他語言的接口,只要您在包含模塊時實現一些基本的功能,就可以免費獲得很多功能。

可枚舉就是一個很好的例子,只要你定義[]和每個當你包括可枚舉你突然得到流行,推等

所以我的直覺有關測試模塊,是,你也許應該測試包含模塊的類,而不是測試模塊本身,除非模塊設計爲不包含在任何內容中,它只是一個代碼存儲機制。

4

在一個模塊中包含一個initialize方法對我來說是非常錯誤的,所以我至少會重新考慮這個方法。我想創建一個新的空類,包含你的模塊,創建該類的一個實例,然後測試該實例:

(http://support.microsoft.com/kb/
class TestClass 
    include MyModule 
end 

class TestMyModule < Unit::Test::TestCase 
    def setup 
    @instance = TestClass.new 
    end 

    def test_my_func 
    assert_equal(5, @instance.my_func) # test the output value given the input params 
    end 
end 
+2

同樣,但更緊湊,我們使用 @instance = Class.new {include MyModule} .new – Kyle 2009-11-20 17:31:23