如何模拟已模拟对象的实例方法?
我需要模拟以下内容:
Class User
def facebook
#returns an instance of a facebook gem
end
end
因此,在我的用户测试中,要访问用户的 facebook 信息,我需要调用 user.facebook.me.info
来检索其信息。如果我想嘲笑这个,我目前正在使用以下内容:
@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"]
这有效,但似乎有点笨拙,有更好的方法吗?
[编辑] 我使用 mocha 作为模拟框架
I need to mock the following:
Class User
def facebook
#returns an instance of a facebook gem
end
end
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] I'm using mocha as mocking framework
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以尝试这样的事情:-
如果你真的想检查所有这些方法是否被调用(我怀疑你没有),你可以执行以下操作:-
它有点冗长,但通常值得给每个模拟反对一个名字:-
我希望有帮助。
You could try something like this :-
If you really want to check that all these methods are called (which I suspect you don't), you could do the following :-
It's a bit more verbose, but it's usually worthwhile giving each mock object a name :-
I hope that helps.
如果您不想检查是否调用了所有方法,您还可以使用不同的模拟替代方法。例如,您可以使用 OpenStruct。
这个解决方案还为您提供了
一个优势,如果您需要测试不同的条件,您可以在测试中更改@facebook 属性。
If you don't want to check that all the methods are called, you can also use different alternatives to mocking. For instance, you can use an OpenStruct.
becomes
This solution also offers you the advantage that you can change the @facebook properties in your tests, if you need to test different conditions.