An alternative to pytest-mock that uses built-in fixture of pytest instead of a separate package is the monkeypatch fixture.
from my_module import func2
def test_func2(monkeypatch):
mocked_value = 4
# create a function that returns the desired mock value
def mock_func_1():
return mocked_value
# patch the module with the mocked function
monkeypatch.setattr(my_module, "func1", mock_func_1)
first = 1
second = 2
actual_value = func2(first, second)
assert actual_value == first + second + mocked_value
One difference I've heard mentioned between pytest-mock
and monkeypatch
is that monkeypatch
allegedly changes the behavior of the mocked function globally within the test environment during runtime, whereas pytest-mock
does so only within the scope of an individual test. If that were true it would be a potential gotcha and a reason to prefer pytest-mock
. But I have not seen this to be the case. The monkeypatched function has to be patched in each test and is not a global patch. This is good because you don't want stateful interdependencies between your unit tests. A reason to prefer monkeypatch
, on the other hand, is to avoid adding additional dependencies to your code base that add to your maintenance burden.
func2
, e.g.assert func2(2, 2) == 9
. That way you can refactor confidently within the module boundary and your tests remain useful. – Congeneric