8

I'm trying to mock a function used within the function I'm testing, but for some reason I'm not seeing the original function always runs, not the one I created as a mock.

The code I'm testing has this type of setup:

def function_being_tested(foo):
    ...
    function_i_want_to_mock(bar)
    ...

def function_i_want_to_mock(bar)
    print("Inside original function")
    ...

I've installed Mock and I've tried using unittest.mock patch

Currently the test file uses this setup:

import mock
from django.test import TestCase


def mock_function_i_want_to_mock(bar):
    print(bar)
    return True


class SupportFunctionsTestCases(TestCase):

    @mock.patch("path.to.function.function_i_want_to_mock", mock_function_i_want_to_mock)
    def test_function_being_tested(self):
        # setup
        result = function_being_tested(test_foo)
        self.assertEqual(result, expected_result)

What then happens is when I run the test, I always get: "Inside original function", not the parameter printed so it's always running the original function.

I've used this exact setup before and it has worked so I'm not sure what's causing this. Probably some wrong setup...

If anyone has a different way of doing this or spots some error, it would be appreciated.

1 Answer 1

16

"path.to.function.function_i_want_to_mock" should be a path to where the function is used, not defined.

So if function_i_want_to_mock is defined in module_A.py but imported and used in module_B.py, which you are testing, then you should use @mock.patch("path.to.module_B.function_i_want_to_mock", ...).

Sign up to request clarification or add additional context in comments.

2 Comments

This solved it! In my previous usage of this the inner functions I was testing were in the same module as those I was mocking so this discrepancy was "hidden" to me. Thank you!
Oh my god, you saved my life! ❤

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.