[英]Python Mocking a function from an imported module
我想了解如何從導入的模塊中@patch
a function。
這是我到目前為止的位置。
應用程序/模擬.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"
測試/模擬測試.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
的未模擬值。 如何模擬我正在導入到被測命名空間的其他包中的方法?
當您使用unittest.mock
包中的patch
裝飾器時,您不是在修補導入模塊的命名空間(在本例中為app.my_module.get_user_name
),而是在 test 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')
標准庫文檔包括一個有用的部分來描述這一點。
雖然 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')
除了 Matti John 的解決方案,您還可以在app/mocking.py
。
# from app.my_module import get_user_name
from app import my_module
def test_method():
return my_module.get_user_name()
if __name__ == "__main__":
print "Starting Program..."
test_method()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.