Python Testing - Mocking different responses for consecutive calls


Python testing tip:

You can specify different responses for consecutive calls to your MagicMock.

It's useful when you want to mock a paginated response.

👇

from unittest.mock import MagicMock


def test_all_cars_are_fetched():
    get_cars_mock = MagicMock()
    get_cars_mock.side_effect = [
        ["Audi A3", "Renault Megane"],
        ["Nissan Micra", "Seat Arona"]
    ]

    print(get_cars_mock())
    # ['Audi A3', 'Renault Megane']
    print(get_cars_mock())
    # ['Nissan Micra', 'Seat Arona']