我想了解如何@patch
从导入的模块中获取函数。
这是我到目前为止的地方。
应用程序/ mocking.py:
from app.my_module import get_user_name
def test_method():
return get_user_name()
if __name__ == "__main__":
print "Starting Program..."
test_method()
应用程序/ my_module / __ init__.py:
def get_user_name():
return "Unmocked User"
测试/ mock-test.py:
import unittest
from app.mocking import test_method
def mock_get_user():
return "Mocked This Silly"
@patch('app.my_module.get_user_name')
class MockingTestTestCase(unittest.TestCase):
def test_mock_stubs(self, mock_method):
mock_method.return_value = 'Mocked This Silly')
ret = test_method()
self.assertEqual(ret, 'Mocked This Silly')
if __name__ == '__main__':
unittest.main()
这并没有工作,我期望的那样。“patched”模块只返回unmocked值get_user_name
。如何从我导入到测试中的命名空间的其他包中模拟方法?
发布于 2018-09-10 12:29:33
虽然Matti John的答案解决了你的问题(也帮助了我,谢谢!),但是,我建议将原始的'get_user_name'函数替换为模拟的函数。这将允许您控制何时更换功能以及何时更换功能。此外,这将允许您在同一测试中进行多次替换。为此,请以非常类似的方式使用“with”语句:
from mock import patch
class MockingTestTestCase(unittest.TestCase):
def test_mock_stubs(self):
with patch('app.mocking.get_user_name', return_value = 'Mocked This Silly'):
ret = test_method()
self.assertEqual(ret, 'Mocked This Silly')
发布于 2018-09-10 13:02:05
当您使用包中的patch
装饰器时,unittest.mock
您没有修补从中导入模块的命名空间(在本例中app.my_module.get_user_name
),您正在测试的命名空间中修补它app.mocking.get_user_name
。
Mock
尝试上面的尝试,如下所示:
from mock import patch
from app.mocking import test_method
class MockingTestTestCase(unittest.TestCase):
@patch('app.mocking.get_user_name')
def test_mock_stubs(self, test_patch):
test_patch.return_value = 'Mocked This Silly'
ret = test_method()
self.assertEqual(ret, 'Mocked This Silly')
标准库文档包含一个描述此内容的有用部分。
https://stackoverflow.com/questions/-100002596
复制相似问题