簡體   English   中英

Python:使用Mock覆蓋類方法

[英]Python: using Mock to override class method

FooObject類只有一個version字段和一個update()方法。

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

我想使用Python的Mock工具重寫unittest的update方法。 我該怎么辦? 我應該使用patch嗎?

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

為此,您可以使用@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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM