nsfyn55 nsfyn55 - 7 months ago 34
Python Question

Python Mocking a function from an imported module

I want to understand how to

a function from an imported module.

This is where I am so far.


from app.my_module import get_user_name

def test_method():
return get_user_name()

if __name__ == "__main__":
print "Starting Program..."


def get_user_name():
return "Unmocked User"


import unittest
from app.mocking import test_method

def mock_get_user():
return "Mocked This Silly"

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__':

This does not work as I would expect. The "patched" module simply returns the unmocked value of
. How do I mock methods from other packages that I am importing into a namespace under test?


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:

from mock import patch

class MockingTestTestCase(unittest.TestCase):

    def test_mock_stubs(self, test_patch):
        test_patch.return_value = 'Mocked This Silly'
        ret = test_method()
        self.assertEqual(ret, 'Mocked This Silly')

The standard library documentation includes a useful section describing this.