4

The pytest-mock patching does not work as expected. My code:

utils.py:

def my_func():
    return 42

classes.py:

from utils import my_func

class MyClass:
    def class_method(self):
        return my_func()

test_classes.py:

import pytest
from classes import MyClass

def test_myclass(mocker):
    mocker.patch("utils.my_func", return_value=21)
    assert MyClass().class_method() == 21

This fails, the return is 42 instead of 21.

felice
  • 1,185
  • 1
  • 13
  • 27

1 Answers1

9

The solution is to change the patching within the test. Instead of

mocker.patch("utils.my_func", return_value=21)

write

mocker.patch("classes.my_func", return_value=21)

because of this line in classes.py: from .utils import my_func.

felice
  • 1,185
  • 1
  • 13
  • 27
  • 2
    thank you for this answer! this can be really counterintuitive especially for those newer to writing unit tests – Derek O Mar 08 '23 at 04:29