摩卡:具有特定参数的存根方法,但不适用于其他参数 [英] Mocha: stubbing method with specific parameter but not for other parameters
问题描述
我只想在给定特定参数值时使用Mocha存根方法,而在给定其他任何值时调用原始方法.
I want to stub a method with Mocha only when a specific parameter value is given and call the original method when any other value is given.
当我这样做时:
MyClass.any_instance.stubs(:show?).with(:wanne_show).returns(true)
我得到
unexpected invocation for MyClass.show?(:other_value)
我也知道,在编写模拟时,可以在不进行"with"调用的情况下对所有参数进行存根,然后给出我的特定模拟.但是然后我必须知道每个调用的返回值,情况并非如此:/
I also know, that I can stub all parameters when writing the mock without the ´with´-call and then give my specific mock. But then I have to know the return value for every call, which is not the case :/
tldr; 是否可以在存根中调用原始方法或仅存入特定参数并保留其他参数?
tldr; Is there a way to call the original method in a stub or to stub just specific parameters and leave the others?
推荐答案
答案取决于您要测试的内容.
The answer depends on what exactly you're testing.
一些注意事项:
1)我总是避免使用stubs.any_instance
.您可以在存根/模拟中具体说明,这可以防止错误的测试阳性结果.
1) I always avoid using stubs.any_instance
. You can be specific in your stubs/mocks, which prevents false testing positives.
2)我更喜欢将间谍与存根一起使用,以主动断言某些东西已经被调用.为此,我们使用 bourne gem.另一种方法是使用模拟程序,它隐式测试是否正在调用某些东西(例如,如果不被调用,将会失败.
2) I prefer using spies along with stubs, to actively assert that something has been called. We use the bourne gem for this purpose. The alternative is to use a mock, which implicitly tests if something is being called (e.g. will fail if it doesn't get called.
所以您的类方法可能看起来像这样(注意,这是RSpec语法):
So your class-method might looks something like this (note, this is RSpec syntax):
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
有很多存根/间谍示例此处.
There are a lot of stub/spy examples here.
希望这会有所帮助.
这篇关于摩卡:具有特定参数的存根方法,但不适用于其他参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!