我想了解如何从导入的模块中创建函数
到目前为止,我就在这里
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\u module/\uuu init\uuu.py:
def get_user_name():
return "Unmocked User"
测试/模拟测试。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”模块只返回未修改的值get_user_name
。如何模拟其他包中的方法,将这些方法导入测试中的命名空间
虽然Matti John的回答解决了您的问题(也帮助了我,谢谢!),但是,我建议将原来的“get_user_name”函数替换为模拟函数。这将允许您控制何时替换该函数以及何时不替换该函数。此外,这将允许您在同一测试中进行多次替换。为此,请以非常相似的方式使用“with”语句:
当您使用来自
unittest.mock
包的patch
装饰器时,您不是在修补模块从中导入的命名空间(在本例中为app.my_module.get_user_name
),而是在测试app.mocking.get_user_name
下的命名空间中修补它要使用
Mock
执行上述操作,请尝试以下操作:标准库文档包括一个有用的section来描述这一点
相关问题 更多 >
编程相关推荐