-->

摩卡:磕碰法的具体参数,但不支持其他参数(Mocha: stubbing method with s

2019-09-03 07:18发布

我想用存根摩卡的方法,只有当一个特定的参数值,并给出调用原始的方法时,给出任何其他值。

当我这样做是这样的:

MyClass.any_instance.stubs(:show?).with(:wanne_show).returns(true)

我得到一个

unexpected invocation for MyClass.show?(:other_value)

我也知道,如果没有'with'呼叫编写模拟的时候,我可以存根的所有参数,然后给我具体的模拟。 但我必须知道每一个电话,这是不是这样的返回值:/

tldr; 有没有一种方法来调用原来的方法存根或存根只是具体参数,离开其他人呢?

Answer 1:

答案取决于正是你测试的内容。

几点注意事项:

1)我总是避免使用stubs.any_instance 。 你可以在特定的存根/模拟考试,以防止虚假的检测阳性。

2)我更喜欢使用间谍与存根一起,积极主张的东西已经被调用。 我们使用伯恩宝石用于这一目的。 另一种方法是使用一个模拟,它隐测试,如果事情被调用(如会失败,如果它被调用。

所以,你的类方法可能看起来是这样的(注意,这是RSpec的语法):

require 'bourne'
require 'mocha'

it 'calls MyClass.show?(method_params)' do
  MyClass.stubs(:show?)

  AnotherClass.method_which_calls_my_class

  expect(MyClass).to have_received(:show?).with('parameter!')
end

class AnotherClass
  def self.method_which_calls_my_class
    MyClass.show?('parameter!')
  end
end

有很多的存根/间谍的例子在这里 。

希望这可以帮助。



文章来源: Mocha: stubbing method with specific parameter but not for other parameters