如何模拟已经模拟对象的实例方法?

编程入门 行业动态 更新时间:2024-10-24 15:23:21
本文介绍了如何模拟已经模拟对象的实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要模拟以下内容:

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"})))

我希望能帮上忙.

更多推荐

如何模拟已经模拟对象的实例方法?

本文发布于:2023-10-31 07:45:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   对象   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!