模拟类:Mock() 还是 patch()?

问题描述 投票:0回答:3

我正在将 mock 与 Python 一起使用,并且想知道这两种方法中哪一种更好(阅读:更多 pythonic)。

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

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

    self.assertTrue(mock.method.called)

方法二:使用patch创建mock。代码如下:

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

    self.assertTrue(instance.method.called)

两种方法都做同样的事情。我不确定其中的差异。

有人可以启发我吗?

python unit-testing mocking
3个回答
209
投票

mock.patch
是一种与
mock.Mock
非常不同的生物。
patch
用模拟对象替换类,并允许您使用模拟实例。看看这个片段:

>>> 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
的方式允许您控制调用的函数中类的使用。一旦你修补了一个类,对该类的引用将完全被模拟实例取代。

当您测试在测试中创建类的新实例的内容时,通常会使用

mock.patch
mock.Mock
实例更清晰,是首选。如果您的
self.sut.something
方法创建了
MyClass
的实例,而不是接收实例作为参数,那么
mock.patch
在这里就合适了。


59
投票

我有一个关于此的 YouTube 视频

简短的回答:当你传递你想要嘲笑的东西时,使用

mock
,如果你不想传递,则使用
patch
。在这两者中,模拟是强烈首选,因为它意味着您正在使用正确的依赖注入来编写代码。

愚蠢的例子:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

25
投票

解释差异并为使用 unittest.mock

提供指导的要点

  1. 如果你想替换被测对象的一些界面元素(传递参数),请使用 Mock
  2. 如果要替换被测对象的某些对象的内部调用和导入模块,请使用补丁
  3. 始终提供您正在模拟的对象的规范
    • 通过补丁,您始终可以提供 autospec
    • 使用 Mock,您可以提供 spec
    • 您可以使用create_autospec代替Mock,它旨在创建具有规范的Mock对象。

在上面的问题中,正确的答案是使用

Mock
,或者更准确地说是
create_autospec
(因为它会将规范添加到您正在模拟的类的模拟方法中),模拟上定义的
spec
如果尝试调用不存在的类的方法(无论签名如何),将会很有帮助,请参阅一些

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

具有定义规范的测试用例使用fail,因为从

something
second
函数调用的方法不是对MyClass的投诉,这意味着-它们捕获错误,而默认的
Mock
将显示。

作为旁注,还有一个选项:使用 patch.object 来模拟调用的类方法。

补丁的良好用例是当类用作函数的内部部分时的情况:

def something():
    arg = 1
    return MyClass.method(arg)

然后你会想使用 patch 作为装饰器来模拟 MyClass。

© www.soinside.com 2019 - 2024. All rights reserved.