【问题标题】:Test modules with Test::Unit使用 Test::Unit 测试模块
【发布时间】:2009-11-18 20:54:26
【问题描述】:

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

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

提前致谢!

【问题讨论】:

  • 如果MyModule 是一个类,那么include MyModule 将引发TypeError。您是否对类和模块感到困惑?

标签: ruby unit-testing module testunit


【解决方案1】:

在模块中包含 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

【讨论】:

  • 类似,但更简洁,我们使用 @instance = Class.new{ include MyModule }.new
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多