我想了解如何@patch
导入模块中的函数。
这是我目前为止的地方。
app/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()
app/my_module/__init__.py:
def get_user_name():
return "Unmocked User"
test/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()
这确实不按我的预期工作。 “已修补”模块仅返回 get_user_name
的未模拟值。如何模拟要导入到正在测试的命名空间的其他包中的方法?
最佳答案
当您使用 unittest.mock
包中的 patch
装饰器时,您是在在正在测试的命名空间中修补它(在本例是 app.mocking.get_user_name
),而不是导入函数的命名空间(本例中是 app.my_module.get_user_name
)。
要执行您使用 @patch
描述的操作,请尝试以下操作:
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')
标准库文档包括一个有用的 section描述这个。
关于Python 从导入的模块中模拟一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134281/