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.
Python code
19 linesimport 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
.
----------------------------------------------------------------------
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
- Use assert_called_once_with to verify exactly one call with the specified arguments.
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.