Search code examples
pythonpython-2.7unit-testingmonkeypatching

Unit testing with mock and patch


I am writing unit tests for a function, f, which imports other functions/classes which the unit test does not (directly) interact with. Is there any way I can patch those functions from the unit test (maybe in set_up())?

For reference, I am using Python 2.7.

From the unittest, I want to modify/patch the behavior of helper.

In unittest file:

def test_some_function():
    assert(some_function() == True)

In some_function() definition

import helper
def some_function():
    foo = helper.do_something()
    return foo & bar

Solution

  • Mocking out a module is fairly standard and documented here. You will see a fairly explicit example of how it is done.

    Furthermore, it is important to understand where to patch, to understand how you properly mock out modules in other scripts.

    To provide you with a more explicit example with reference to your code, you want to do something like this:

    import unittest
    from unittest.mock import patch
    
    import module_you_are_testing
    
    class MyTest(unittest.TestCase):
    
        @patch('module_you_are_testing.helper')
        def test_some_function(self, helper_mock):
            helper_mock.do_something.return_value = "something"
            # do more of your testing things here
    

    So, the important thing to remember here, is that you are referencing helper with respect to where you are testing. Look at the sample code I provided and you will see we are importing module_you_are_testing. So, it is with respect to that you mock.