How to Use mock.assert_called_with in Python

Verify that a MagicMock received a call with specific positional and keyword arguments using assert_called_with in unittest.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

19 lines
Python 3.9+
import unittest
from unittest.mock import MagicMock

class TestMockAssertions(unittest.TestCase):
    def test_assert_called_with(self):
        # Create a mock object
        mock = MagicMock()

        # Call the mock with specific arguments
        mock.send_email("alice@example.com", subject="Greetings", body="Hello!")

        # Assert it was called with exactly those arguments
        mock.send_email.assert_called_with(
            "alice@example.com", subject="Greetings", body="Hello!"
        )
        print("Test passed: assert_called_with matched the call.")

if __name__ == "__main__":
    unittest.main()

Output

stdout
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Test passed: assert_called_with matched the call.

How it works

assert_called_with checks the most recent call to the mock, comparing both positional and keyword arguments for exact equality. It raises an AssertionError if the last call doesn't match, so it's perfect for verifying argument passing in unit tests. Use assert_called_once_with when you want to confirm the mock was called exactly once with those arguments. Remember that call order matters — this assertion only inspects the latest invocation.

Common mistakes

  • Using assert_called_with when the mock was called multiple times — it only checks the last call.
  • Confusing assert_called_with with assert_called_once_with (the latter also verifies call count).
  • Forgetting to mock the object before calling the assertion, causing TypeError on real objects.

Variations

  1. Use assert_called_once_with to verify exactly one call with the specified arguments.
  2. Use call_args or call_args_list for more detailed inspections of multiple calls.

Real-world use cases

  • Verify that an email service mock receives the correct recipient and subject in a notification test.
  • Confirm an API client mock passes expected payload fields when testing a data syncing function.
  • Validate that a logging mock is called with the right severity level and message during error handling tests.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.