How To Easily Resolve The "Fixture 'Mocker' Not Found" Error in Pytest

Testing is a pivotal pillar in the expansive world of Python development, ensuring code robustness, reliability, compatibility and peace of mind.

One key aspect of testing is “mocking” — a technique allowing parts of a system to be replaced with controlled stand-ins, enhancing test isolation and control.

In this context, you may have come across tools like the ‘mocker’ fixture, that makes mocking in Pytest easy.

However, have you encountered the common pitfall fixture ‘mocker’ not found error?

Annoying but simple to resolve, we got you covered.

In this article, we dive deep into this issue, understanding how to debug the fixture ‘mocker’ not found error.

We share some guardrails to ensure you don’t fall for the fixture ‘mocker’ not found error.

By the end, you’ll have a better understanding of the mocker fixture and how to adeptly navigate its intricacies to optimize your tests.

Are you ready?

What is the mocker Fixture in Pytest?

The mocker fixture is a fixture provided by Pytest, built atop Python’s built-in unittest.mock method.

It is available in Pytest via the pytest-mock plugin.

Instead of relying on direct imports, this fixture is delivered through dependency injection.

In simpler terms, Pytest is responsible for generating the mocker instance and handing it over to the test method during test execution.

This fixture offers a more user-friendly interface than the standard unittest.mock class found in Unittest .

When Pytest encounters a test that has a “mocker” parameter, it automatically populates it with the outcome of the “mocker” function.

Common Scenarios Leading to “fixture ‘mocker’ not found” (+ How to Solve)

Here are some common scenarios leading to this annoying error.

Not having pytest-mock installed

The most common cause of this error is simply not having the pytest-mock plugin installed.

mocker is a part of this plugin, and without it, pytest won’t recognize the fixture.

Ensure you’ve installed it using the command pip install pytest-mock or just stick it in your requirements.txt file to be installed when creating your virtual environment.

A failure to install this plugin can very well lead to this error and is by far the biggest reason.

Misspelling the fixture name

As silly as this sounds, misspelling the fixture name- using mock instead of mocker can cause issues.

Incorrect Import

Once you’ve installed pytest-mock, you don’t need to import it explicitly in your test files.

The mocker fixture will be automatically recognized by pytest once the plugin is installed.

If you’re trying to import mocker directly, this could cause confusion or errors.

Misconfiguration in pytest Settings or Initialization Files

In some cases, if you have a pytest.ini, pyproject.toml, or setup.cfg file, there might be configurations that disable plugins or fixtures.

Ensure that there’s no configuration line that might be causing pytest-mock to be overlooked or disabled.

If you need a refresher on pytest.ini and how to define config files, this article on Pytest Ini is a foundational read.

Custom Conftest Issues

pytest allows the use of a conftest.py file to define custom fixtures and plugins for a test suite. If you need a refresher on Conftest, check out this article on Pytest Conftest.

If there’s an error or misconfiguration in this file, it might overshadow or conflict with the built-in mocker fixture.

Plugin Conflicts

On rare occasions, there might be other pytest plugins that conflict with pytest-mock.

If you’ve recently added a new plugin and started facing this issue, consider checking for compatibility issues between plugins.

Environment or Virtual Environment Issues

If you’re using virtual environments (like venv or conda), make sure the environment you’re running pytest from has pytest-mock installed.

It’s possible to install it in one environment and inadvertently run tests from another. Python and Pytest rely on the PATH environment variable.

If there are misconfigurations or multiple Python installations, it might cause pytest to look in the wrong place for its plugins.

To remedy the error, start by checking the installation of pytest-mock in your current environment.

Then, inspect configuration files for any discrepancies.

Finally, ensure there are no conflicts or overshadowing from other plugins or custom fixtures.

Example Code

Let’s do a quick demonstration of just how simple it is to forget to install an important plugin and wonder why it doesn’t work.

src/api_module.py

1
2
3
4
5
6
7
8
9
10
11
import requests  

API_URL = (
"https://opentdb.com/api.php?amount=1&category=11&difficulty=easy&type=multiple"
)


def get_trivia_questions() -> list:
"""Get trivia questions from an API."""
response = requests.get(API_URL)
return response.json()

Here we have a very simple piece of code that gets Trivia questions from a FREE Trivia API.

Running the code produces a simple, expected, non-deterministic response.

1
python src/api_module.py

fixture-mocker-not-found-run-api

Testing Example Code

Our test code looks something like this.

If you’re not familiar with Mocking I highly recommend you read these articles on Pytest Mocking and Monkeypatching, which offer a solid introduction with clear examples.

tests/test_api_module.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import pytest  
import requests
from src.api_module import get_trivia_questions, API_URL


def test_get_trivia_questions_mocked(mocker):
mock_response = {
"response_code": 0,
"results": [
{
"category": "Entertainment: Film",
"type": "multiple",
"difficulty": "easy",
"question": "This movie contains the quote, "Nobody puts Baby in a corner."",
"correct_answer": "Dirty Dancing",
"incorrect_answers": [
"Three Men and a Baby",
"Ferris Bueller's Day Off",
"Pretty in Pink",
],
}
],
}
mocker.patch(
"src.api_module.requests.get"
).return_value.json.return_value = mock_response
response = get_trivia_questions()
requests.get.assert_called_once_with(API_URL)
assert response == mock_response

In this test, we’ve mocked the API response and asserted that our URL was called using the assert_called_once_with method.

We also check the mock response matches our expectations.

Let’s test this.

fixture-mocker-not-found-fail

We get the expected fixture ‘mocker’ not found error.

Now let’s install the requirements using

1
pip install -r requirements.txt

Which also includes the pytest-mock library.

Let’s run the test again.

fixture-mocker-not-found-success

Great! Test passed!.

Conclusion

In this short but interesting article, we learned about the mocker fixture in Pytest using a simple example (trivia question generator).

If you experience the common fixture "mocker" not found error, the first step is to ensure your pyest-mock fixture is installed.

This is by far the most commonly experienced cause of the error. There are also less common causes like environment mismatches, incorrect imports or spelling.

There have been issues reported with tools like Tox where they fail to re-generate the venv if the requirements.txt file changes also leading to this error.

However, I believe these have been fixed in v4+.

I hope this article saved you some debugging time. Happy mocking!

If you have any ideas for improvement or like me to cover any topics please comment below or send me a message via Twitter, GitHub or Email.

Additional Reading

Introduction to Pytest Mocking - What It Is and Why You Need It

The Ultimate Guide To Using Pytest Monkeypatch with 2 Code Examples

8 Useful Pytest Plugins To Make Your Python Unit Tests Easier, Faster and Prettier

Pytest Conftest With Best Practices And Real Examples

What Is pytest.ini And How To Save Time Using Pytest Config