pythonpytesttddpython-unittestpytest-mock

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?


Solution

  • 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.