How to Use mocker Fixture in pytest for Easy Mocking
In pytest, use the
mocker fixture from the pytest-mock plugin to replace parts of your code with mocks during tests. Simply add mocker as a test argument and call methods like mocker.patch() to mock functions or objects.Syntax
The mocker fixture is provided by the pytest-mock plugin. You use it by adding mocker as a parameter to your test function. Then you can call methods like mocker.patch(target, new=mocked_value) to replace the target with a mock.
Key parts:
mocker: the fixture that gives mocking toolspatch(): replaces a function or object temporarilytarget: the full path to the function or object to mocknew: the value or mock to use instead
python
import module def test_example(mocker): mocked_func = mocker.patch('module.function') mocked_func.return_value = 42 result = module.function() assert result == 42
Example
This example shows how to mock a function get_data from a module data_source. The mock replaces the real function to return a fixed value during the test.
python
import pytest # Imagine this is in data_source.py # def get_data(): # return 'real data' import data_source def test_mock_get_data(mocker): mocker.patch('data_source.get_data', return_value='mocked data') result = data_source.get_data() assert result == 'mocked data'
Output
============================= test session starts =============================
collected 1 item
test_example.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when using mocker include:
- Not installing or importing
pytest-mockplugin, somockeris unavailable. - Using incorrect target strings in
patch()(must be full import path). - Forgetting to set
return_valueor side effects on the mock. - Trying to patch objects not imported or used in the tested code's namespace.
python
import module def test_wrong_patch(mocker): # Wrong target string - will not patch correctly mocker.patch('wrong.module.func', return_value=10) # Correct way def test_right_patch(mocker): mock = mocker.patch('module.func') mock.return_value = 10 assert module.func() == 10
Quick Reference
- mocker.patch(target, new=...): Replace target with new mock or value.
- mocker.spy(target): Wrap target to spy calls without changing behavior.
- mocker.stub(): Create a simple mock object.
- Always use full import path for
target. - Set
return_valueorside_effecton mocks to control behavior.
Key Takeaways
Use the pytest-mock plugin to get the mocker fixture in pytest tests.
Add mocker as a test function argument to access mocking methods like patch().
Always patch using the full import path of the function or object you want to mock.
Set return_value or side_effect on mocks to control their behavior during tests.
Check that pytest-mock is installed and imported to avoid fixture errors.