如何在 Ruby 中模拟方法调用

How to mock a method call in Ruby

我正在为 Class A 编写一个名为 m() 的测试方法。

m() 通过一个名为 'b' 的 B 实例调用 Class B 上的 f(),但我使用 -

模拟该方法调用
def test_m 
@a = A.new
b_mock = MiniTest::Mock.new
b_mock.expect(:f, 'expected_output')
def b_mock.f()
return 'expected output'
end
@a.b = b_mock
end

现在 A 有另一个方法 m1(),如何使用上述方法或 Minitest 的更好方法模拟调用它并获得恒定输出?

错误-

NoMethodError: unmocked method :get_group_by_name, expected one of [:]

您可以使用 MiniTest Object#stub 方法,它会在块的持续时间内重新定义方法结果。

require 'minitest/mock'

class A
  def m1
    m2
    'the original result'
  end

  def m2
    'm2 result'
  end
end

@a = A.new
@a.stub :m1, "the stubbed result" do

  puts @a.m1  # will print 'the stubbed result'
  puts @a.m2

end

阅读更多:http://www.rubydoc.info/gems/minitest/4.2.0/Object:stub