编程语言
首页 > 编程语言> > Python Mock在类中修补多个方法

Python Mock在类中修补多个方法

作者:互联网

我试图在一个类中修补多个方法.这是我的简化设置

Hook.py定义为

class Hook():
    def get_key(self):
        return "Key"

    def get_value(self):
        return "Value"

HookTransfer.py定义为

from Hook import Hook

class HookTransfer():
    def execute(self):
        self.hook = Hook()
        key = self.hook.get_key()
        value = self.hook.get_value()
        print(key)
        print(value)

我想在Hook类中模拟get_key和get_value方法.以下工作即打印New_Key和New_Value

from HookTransfer import HookTransfer
import unittest
from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch('HookTransfer.Hook.get_key', return_value="New_Key")
    @mock.patch('HookTransfer.Hook.get_value', return_value="New_Value")
    def test_execute1(self, mock_get_key, mock_get_value):
        HookTransfer().execute()

if __name__ == '__main__':
    unittest.main()

但事实并非如此.它打印< MagicMock name ='Hook().get_key()'id ='4317706896'>和< MagicMock name ='Hook().get_value()'id ='4317826128'>

from HookTransfer import HookTransfer
import unittest
from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch('HookTransfer.Hook', spec=True)
    def test_execute2(self, mock_hook):
        mock_hook.get_key = mock.Mock(return_value="New_Key")
        mock_hook.get_value = mock.Mock(return_value="New_Value")
        HookTransfer().execute()

if __name__ == '__main__':
    unittest.main()

直观地看起来第二个也应该起作用但它没有.你能帮忙解释一下为什么没有.我怀疑它与“where to patch”有关但我无法清晰.

解决方法:

你需要的是:

嘲笑班克,

from HookTransfer import HookTransfer
from Hook import Hook

import unittest
try:
    import mock
except ImportError:
    from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch.object(Hook, 'get_key', return_value="New_Key")
    @mock.patch.object(Hook, 'get_value', return_value="New_Value")
    def test_execute1(self, mock_get_key, mock_get_value):
        HookTransfer().execute()

if __name__ == "__main__":
    unittest.main()

标签:python-unittest,python-mock,python
来源: https://codeday.me/bug/20190823/1701741.html