Python - assert that a mock function was called with certain arguments


Python tip:

You can assert that the method on a MagicMock object was called with certain arguments.

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_with

For example, you can mock an email service and assert that the send method was called with specific values:

from unittest.mock import MagicMock


def place_order(user, items, email_service):
    print(f"Place order for user {user}")
    print(f"With items: {items}")
    email_service.send(user, "Order placed.")


def test_place_order():
    email_service = MagicMock()

    place_order("[email protected]", ["Computer", "USB drive", "Vodka"], email_service)
    email_service.send.assert_called_with("[email protected]", "Order placed.")