模拟与魔术模拟 [英] Mock vs MagicMock

查看:67
本文介绍了模拟与魔术模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是 MagicMock Mock 的超集,它会自动执行魔术方法",从而无缝地为列表,迭代等提供支持...那么简单的 Mock 存在的原因是什么?难道这不是 MagicMock 的精简版,实际上可以忽略吗? Mock 类是否知道在 MagicMock 中不可用的任何技巧?

My understanding is that MagicMock is a superset of Mock that automatically does "magic methods" thus seamlessly providing support for lists, iterations and so on... Then what is the reason for plain Mock existing? Isn't that just a stripped down version of MagicMock that can be practically ignored? Does Mock class know any tricks that are not available in MagicMock?

推荐答案

存在普通 Mock 的原因是什么?

模拟的作者Michael Foord在Pycon 2011(31:00)上对一个非常类似的问题进行了回答):

What is the reason for plain Mock existing?

Mock's author, Michael Foord, addressed a very similar question at Pycon 2011 (31:00):

问:为什么MagicMock做了一件单独的事情,而不仅仅是将功能折叠到默认的模拟对象中?

Q: Why was MagicMock made a separate thing rather than just folding the ability into the default mock object?

A:一个合理的答案是MagicMock的工作方式是通过创建新的Mocks和 设置它们,因此,如果每个新的模拟都创建了一堆新的模拟,并且 将这些设置为协议方法,然后将所有这些协议方法 创建了更多模拟,并在其协议方法上进行了设置, 您有无限的递归...

A: One reasonable answer is that the way MagicMock works is that it preconfigures all these protocol methods by creating new Mocks and setting them, so if every new mock created a bunch of new mocks and set those as protocol methods and then all of those protocol methods created a bunch more mocks and set them on their protocol methods, you've got infinite recursion...

如果您想将模拟作为容器对象访问,该怎么办? 错误-您不希望它起作用吗?如果每个模拟都自动 有了每种协议方法,那么要做起来就困难得多 那.而且,MagicMock还可以为您完成一些预配置, 设置可能不合适的返回值,所以我认为 拥有所有东西的便利会更好 已预先配置并可供您使用,但您也可以选择普通的 模拟对象并只需配置要存在的魔术方法即可.

What if you want accessing your mock as a container object to be an error -- you don't want that to work? If every mock has automatically got every protocol method, then it becomes much more difficult to do that. And also, MagicMock does some of this preconfiguring for you, setting return values that might not be appropriate, so I thought it would be better to have this convenience one that has everything preconfigured and available for you, but you can also take a ordinary mock object and just configure the magic methods you want to exist...

简单的答案是:如果可以的话,只需在所有地方使用MagicMock 您想要的行为.

The simple answer is: just use MagicMock everywhere if that's the behavior you want.

这篇关于模拟与魔术模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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