Question
I want to understand how to @patch a function from an imported module. This is where I am so far.
- 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()
- def get_user_name():
- return "Unmocked User"
- import unittest
- from unittest.mock import patch
- from app.mocking import test_method
- class MockingTestTestCase(unittest.TestCase):
- @patch('app.my_module.get_user_name')
- def test_mock_stubs(self, mock_method):
- mock_method.return_value = 'Mocked This Silly'
- ret = test_method()
- self.assertEqual(ret, 'Mocked This Silly')
How-To
When you are using the patch decorator from the unittest.mock package you are not patching the namespace the module is imported from (in this case app.my_module.get_user_name) you are patching it in the namespace under test app.mocking.get_user_name. To do the above with Mock try something like the below:
- import unittest
- from unittest.mock import patch
- from app.mocking import test_method
- class MockingTestTestCase(unittest.TestCase):
- @patch('app.mocking.get_user_name')
- def test_mock_stubs(self, mock_method):
- mock_method.return_value = 'Mocked This Silly'
- ret = test_method()
- self.assertEqual(ret, 'Mocked This Silly')
沒有留言:
張貼留言