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 似乎覆盖/生成了一个初始化方法。所以我想知道测试模块的最佳方法是什么?

我还想知道我的模块此时是否应该成为一个类,因为初始化方法是用于初始化某些东西的状态。意见?

提前致谢 !

4

2 回答 2

4

在模块中包含一个initialize方法对我来说是非常错误的,所以我至少会重新考虑这一点。

不过,为了更直接地回答您关于将其作为模块进行测试的问题,我将创建一个新的空类,将您的模块包含在其中,创建该类的实例,然后针对该实例进行测试:

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
于 2009-11-18T21:16:52.977 回答
3

是的,您的初始化绝对应该表明您要去上课。ruby 中的模块通常感觉就像其他语言中的接口,只要在包含模块时实现一些基本的东西,你就会免费获得很多东西。

Enumerable 就是一个很好的例子,只要你定义 [] 并且每次包含 Enumerable 时,你都会突然得到 pop、push 等。

所以我对测试模块的直觉是,你可能应该测试包含模块的类,而不是测试模块本身,除非模块被设计为不包含在任何东西中,它只是一种代码存储机制。

于 2009-11-18T21:14:30.610 回答