Python: 使用 Mock 覆盖 class 方法

Python: using Mock to override class method

有一个 FooObject class 只有一个 version 字段和一个 update() 方法。

class FooObject(models.Model):
  version = models.CharField(max_length=100)

我想使用 Python 的 Mock 工具覆盖单元测试的 update 方法。我该怎么做?我应该使用 patch 吗?

foo_object.update = Mock(self.version = '123')

为此,您可以使用 @patch 模拟 class 函数

from mock import patch

# Our class to test
class FooObject():
    def update(self, obj):
        print obj

# Mock the update method
@patch.object(FooObject, 'update')
def test(mock1):
    # test that the update method is actually mocked
    assert FooObject.update is mock1
    foo = FooObject()
    foo.update('foo')
    return mock1

# Test if the mocked update method was called with 'foo' parameter
mock1 = test()
mock1.assert_called_once_with('foo')

您甚至可以模拟更多这样的函数:

from mock import patch

class FooObject():
    def update(self, obj):
        print obj

    def restore(self, obj):
        print obj

@patch.object(FooObject, 'restore')
@patch.object(FooObject, 'update')
def test(mock1, mock2):
    assert FooObject.update is mock1
    assert FooObject.restore is mock2
    foo = FooObject()
    foo.update('foo')
    foo.restore('bar')
    return mock1, mock2

mock1, mock2 = test()
mock1.assert_called_once_with('foo')
mock2.assert_called_once_with('bar')