Pritam Bohra
Pritam Bohra

Reputation: 4329

What are the differences between unittest.mock, mock, mocker and pytest-mock?

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?

Upvotes: 29

Views: 20313

Answers (2)

Simon Hawe
Simon Hawe

Reputation: 4539

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.

Upvotes: 16

Tero Y
Tero Y

Reputation: 66

@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)

Upvotes: 3

Related Questions