如何模拟已经模拟对象的实例方法? [英] How to mock an instance method of an already mocked object?

查看:144
本文介绍了如何模拟已经模拟对象的实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要模拟以下内容:

Class User
  def facebook
    #returns an instance of a facebook gem
  end
end

因此,在我的用户测试中,要访问用户的Facebook信息,我需要调用user.facebook.me.info来检索其信息.如果我想模拟这个,我目前正在使用以下内容:

So in my User tests, to access the User's facebook info I need to call user.facebook.me.info to retrieve its info. If I want to mock this, I'm currently using the following:

@user = Factory(:user)
facebook = mock()
me = mock()
me.expects(:info).returns({"name" => "John Doe"})
facebook.expects(:me).returns(me)
@user.expects(:facebook).returns(facebook)
assert_equal "John Doe", @user.facebook.me.info["name"]

这可行,但似乎有点笨拙,是否有更好的方法来做到这一点?

This works but seems a bit unwieldy, is there a better way to do this ?

[edit]我正在使用摩卡咖啡作为模拟框架

[edit] I'm using mocha as mocking framework

推荐答案

您可以尝试以下方法:-

You could try something like this :-

user = Factory(:user)
user.stubs(:facebook => stub(:me => stub(:info => {:name => "John Doe"})))

如果您真的想检查所有这些方法是否都被调用(我怀疑您没有),则可以执行以下操作:-

If you really want to check that all these methods are called (which I suspect you don't), you could do the following :-

user = Factory(:user)
user.expects(:facebook => mock(:me => mock(:info => {:name => "John Doe"})))

这有点冗长,但是通常值得给每个模拟对象起一个名字:-

It's a bit more verbose, but it's usually worthwhile giving each mock object a name :-

user = Factory(:user)
user.stubs(:facebook => stub('facebook', :me => stub('me', :info => {:name => "John Doe"})))

我希望能帮上忙.

这篇关于如何模拟已经模拟对象的实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆