Search code examples
pythonunit-testingmockingpython-mock

How can I mock an external function within a method in a class


I need some help on mock.

I have following code in mymodule.py:

from someModule import external_function

class Class1(SomeBaseClass):
    def method1(self, arg1, arg2):
        external_function(param)

Now I have test code:

import mock
from django.test import TestCase

from mymodule import class1
class Class1Test(TestCase) 
    def test_method1:
        '''how can I mock external_function here?'''

Solution

  • You would write:

    class Class1Test(TestCase):
    
        @mock.patch('mymodule.external_function')
        def test_method1(self, mock_external_function):
            pass
    

    Looking at mymodule the function external_function is directly imported. Hence you need to mock mymodule.external_function as that's the function that will be called when method1 is executed.