模拟类:Mock()或patch()? [英] Mocking a class: Mock() or patch()?

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

问题描述

我正在将模拟与Python配合使用,并且想知道这两种方法中哪种更好(阅读:更多pythonic).

I am using mock with Python and was wondering which of those two approaches is better (read: more pythonic).

方法一:只需创建一个模拟对象并使用它即可.代码如下:

Method one: Just create a mock object and use that. The code looks like:

def test_one (self):
    mock = Mock()
    mock.method.return_value = True 
    self.sut.something(mock) # This should called mock.method and checks the result. 
    self.assertTrue(mock.method.called)

方法二:使用补丁程序创建模拟.代码如下:

Method two: Use patch to create a mock. The code looks like:

@patch("MyClass")
def test_two (self, mock):
    instance = mock.return_value
    instance.method.return_value = True
    self.sut.something(instance) # This should called mock.method and checks the result. 
    self.assertTrue(instance.method.called)

这两种方法都做同样的事情.我不确定这些差异.

Both methods do the same thing. I am unsure of the differences.

有人可以启发我吗?

推荐答案

mock.Mock完全不同. patch 替换为带有模拟对象的类,并允许您使用模拟实例.看看这个片段:

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch替换MyClass的方式使您可以控制所调用函数中类的使用.修补类后,对该类的引用将完全由模拟实例替换.

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch通常在测试要在测试内部创建类的新实例的对象时使用. mock.Mock实例更清晰,是首选.如果您的self.sut.something方法创建了MyClass的实例而不是将实例作为参数接收,则mock.patch在这里很合适.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

这篇关于模拟类:Mock()或patch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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