有FooObject
个课程,只有一个version
字段和一个update()
方法。
class FooObject(models.Model):
version = models.CharField(max_length=100)
我想使用Python的update
工具覆盖unittest的Mock
方法。我该怎么办?我应该使用patch
吗?
foo_object.update = Mock(self.version = '123')
答案 0 :(得分:4)
要做到这一点,您可以使用@patch来模拟类函数
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')