unittest.mock vs mock vs mocker vs pytest-mock

Question:

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?

Asked By: Pritam Bohra

||

Answers:

So pytest-mock is a thin wrapper around mock and 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.

Answered By: Simon Hawe

@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)
Answered By: Tero Y