我想了解如何從導入的模塊中@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 “嘲笑這個傻”@patch(“app.my_module.get_user_name”)類MockingTestTestCase(unittest.TestCase):def test_mock_stubs(self,mock_method):mock_method.return_value =“嘲笑這個傻”)ret = test_method()self.assertEqual (ret, "Mocked This Silly") if __name__ == "__main__": unittest.main()
這不按我的預期工作。 “已修補”模塊僅返回 get_user_name
的未模擬值。如何模擬要導入到正在測試的命名空間的其他包中的方法?