我试图在一个类中修补多个方法。这是我的简化设置
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()
但是,事实并非如此。它打印
并
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()
凭直觉,似乎第二个也应该工作,但事实并非如此。您能否解释一下为什么不这样做。我怀疑这与“修补位置”有关,但是我无法弄清楚。
您需要的是:
嘲笑钩子,
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()