CodeBlanks Logo Icon CodeBlanks

assert_called

Learn call verification with assert_called_with.

assert_called

To check whether a Mock was called, use the assert_called family. The most basic is assert_called(): it passes silently if called at least once; it raises AssertionError if not called.

Stricter checks: assert_called_once() exactly once; assert_called_with(arg) with specific arguments; assert_called_once_with(arg) exactly once and with specific arguments.

m = Mock()
m(5)
m.assert_called_with(5)  # passes
m.assert_called_with(6)  # raises

These checks verify that the mocked function was called with the right arguments; they inspect fake-object behavior at the end of the test.

Call arguments and order

You can read a Mock's call history with call_args_list. Each entry is a tuple holding the positional and keyword arguments of one call.

This is handy to check call order and the arguments of each call. If a function was called first with (5,) then with (6,), call_args_list lists both.

This helps in multi-call scenarios where simple assert_called_with is not enough.

Practice Check with assert_called_with

Import Mock from unittest.mock. Create m = Mock(); call m("Ayşe"). Add the check m.assert_called_with("Ayşe"). Finally print print("ok").

Starter code

main.py
# import Mock from unittest.mock
# create Mock m; call with "Ayşe"
# check with assert_called_with("Ayşe")
# print "ok"

Sample solution

main.py
from unittest.mock import Mock

m = Mock()
m("Ayşe")
m.assert_called_with("Ayşe")
print("ok")

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the assertion methods

Term Meaning
assert_called() At least once
assert_called_once() Exactly once
assert_called_with(x) With specific arg
assert_called_once_with(x) Exactly once with specific

2 When does assert_called_once() raise?

  • If the Mock was never called
  • If the Mock was called more than once
  • Both if never called and if called more than once Correct answer
  • If the Mock was called once

Explanation: assert_called_once() expects exactly one call; otherwise it raises.

3 assert_called_with call

Question
from unittest.mock import Mock

m = Mock()
m(5)
m.____(5)
Answer
from unittest.mock import Mock

m = Mock()
m(5)
m.assert_called_with(5)

Explanation: m.assert_called_with(5) checks the Mock was called with 5.

All lessons in Advanced