简体   繁体   English

你如何存根特定模拟实例的所有方法

[英]How do you stub all methods of a particular mock instance

I have a particular mock that is being handled by a third party.我有一个由第三方处理的特定模拟。 I just want to check that the same mock has been returned back.我只想检查是否已返回相同的模拟。

However, the third party calls array methods and save methods that my test doesnt really care about.但是,第三方调用我的测试并不真正关心的数组方法和保存方法。 Is there a way to tell my mock that it expects/stub all methods to do with that particular mock instance?有没有办法告诉我的模拟它期望/存根与该特定模拟实例有关的所有方法?

eg.例如。

user = mock(User)
user.stub_all

Thanks!谢谢!

EDIT编辑

More info about the problem:有关该问题的更多信息:

Test:测试:

  it "creating an invitation should return invitation" do
    invitation = mock_model(Invitation)
    invitation.stub(:[]=)
    invitation.stub(:save)
    Invitation.stub(:create).and_return(invitation)
    @user.create_invitation
    @user.create_invitation.should == invitation        
  end

Code being tested:正在测试的代码:

 def create_invitation
    invitation = Invitation.create
    self.invitations.push(invitation)
    return invitation
  end

I need to mock the following which are not directly related to what I am testing:我需要模拟以下与我正在测试的内容没有直接关系的内容:

invitation.stub(:[]=)
invitation.stub(:save)

The answer is答案是

user = mock(User).as_null_object

but in general this approach means your objects are too large and your tests aren't granular enough但总的来说,这种方法意味着您的对象太大并且您的测试不够细化

I came across this accidentally - but the 'blessed' way of doing this (now) is using the spy method, which essentially is the same thing as above:我偶然遇到了这个 - 但是这样做的“祝福”方式(现在)是使用spy方法,它本质上与上面相同:

reference: https://thoughtbot.com/blog/a-closer-look-at-test-spies参考: https : //thoughtbot.com/blog/a-closer-look-at-test-spies

You don't have to stub out any methods that the class implements already.您不必存根该类已经实现的任何方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM