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?

1

2 Answers

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.

2

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.