18

I am new to Python development, I am writing test cases using pytest where I need to mock some behavior. Googling best mocking library for pytest, has only confused me. I have seen unittest.mock, mock, mocker and pytest-mock. Not really sure which one to use. Can someone please explain me the difference between them and also recommend me one?

nbro
  • 15,395
  • 32
  • 113
  • 196
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72
  • 3
    `mock` was a third-party package for Python 2.7 first, then became part of the standard library in Python 3, available as `unittest.mock`. `pytest-mock` is a `pytest` plugin which offers a `mocker` fixture which is a wrapper around `unittest.mock`, as pointed out in the answer below, but with additional features. For example, it automatically reverts all patches made in the test, on test teardown, ensuring test isolation. Beware though that `mocker` can be used in `pytest`-style tests only, e.g. it won't be recognized if you use another test runner. – hoefling Jan 28 '22 at 12:42

2 Answers2

11

pytest-mock is a thin wrapper around mock.

mock is since python 3.3. actually the same as unittest.mock.

I don't know if mocker is another library, I only know it as the name of the fixture provided by pytest-mock to get mocking done in your tests.

I personally use pytest and pytest-mock for my tests, which allows you to write very concise tests like

from pytest_mock import MockerFixture

@pytest.fixture(autouse=True)
def something_to_be_mocked_everywhere(mocker):
    mocker.patch()


def tests_this(mocker: MockerFixture):
    mocker.patch ...
    a_mock = mocker.Mock() ...
    ...

But this is mainly due to using fixtures, which is already pointed out is what pytest-mock offers.

nbro
  • 15,395
  • 32
  • 113
  • 196
Simon Hawe
  • 3,968
  • 6
  • 14
0

@NelsonGon you can use the unittest mocks with pytest, e.g.

def test_app_uses_correct_transformer(monkeypatch):
    mock_transformer = MagicMock()
    mock_transformer.return_value = None
    monkeypatch.setattr("app.transformer", mock_transformer)
Tero Y
  • 36
  • 3