CodeBlanks Logo Icon CodeBlanks

side_effect

Learn behavior imitation with side_effect.

side_effect

side_effect lets a Mock behave differently on each call. Three main uses: a list is returned in order; a function is called; an exception is raised.

m = Mock()
m.side_effect = [1, 2, 3]
m()  # 1
m()  # 2
m()  # 3

return_value returns the same thing every call; side_effect varies across calls. This is useful for mimicking sequential responses or errors.

Function and exception responses

If side_effect is a function, the Mock calls it on each call; the returned value becomes the Mock call result. This is useful for producing different outputs based on the call arguments.

If an exception instance is given, calling the Mock raises that exception. This is used to test error paths.

m.side_effect = lambda x: x * 2
m(5)  # 10

m.side_effect = RuntimeError("boom")
m()  # raises RuntimeError

Using side_effect instead of return_value, you can control call order and arguments.

Practice Sequential calls with side_effect

Import Mock from unittest.mock. Create m = Mock(); set m.side_effect = [1, 2, 3]. Call print(m()), print(m()) and print(m()).

Starter code

main.py
# import Mock from unittest.mock
# create Mock m; set side_effect list [1, 2, 3]
# print m() three times

Sample solution

main.py
from unittest.mock import Mock

m = Mock()
m.side_effect = [1, 2, 3]
print(m())
print(m())
print(m())

Expected output

1
2
3

Questions and answers

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

1 What happens when side_effect = [1, 2, 3]?

  • Every call returns 1
  • Calls return 1, 2, 3 in order Correct answer
  • It returns the list as is
  • It always returns 3

Explanation: With a list, side_effect returns the next item on each call.

2 side_effect with exception

Question
from unittest.mock import Mock

m = Mock()
m.____ = ValueError("hata")
Answer
from unittest.mock import Mock

m = Mock()
m.side_effect = ValueError("hata")

Explanation: With side_effect = ValueError(...) the call raises this exception.

3 Match the side_effect types

Term Meaning
[1, 2, 3] Sequential return
lambda x: x*2 Function call
ValueError(...) Raises exception
return_value Fixed return

All lessons in Advanced