如何在ruby中模拟模块中的方法?

时间:2017-01-26 10:10:37

标签: ruby unit-testing mocking

我有number_module.rb内容:

def power2(x)
  x * x
end

和测试用例tc_number.rb

require_relative('number_module')
require "test/unit"
require 'mocha/test_unit'

class TestSimpleNumber < Test::Unit::TestCase

  def test_simple
    assert_equal(4, power2(2) ) # how to mock power2 to return 3?
  end

end

为了练习模拟,我想在测试用例中模拟power2以返回3而不是powering by 2我该怎么做?

1 个答案:

答案 0 :(得分:5)

documentation开始,您可以使用brew reinstall apr-util

expects(:method_name).returns(result)

测试按预期失败:

def power2(x)
  x * x
end
require "test/unit"
require 'mocha/test_unit'

class TestSimpleNumber < Test::Unit::TestCase
  def test_simple
    expects(:power2).returns(3)
    assert_equal(4, power2(2) )
  end
end