CodeBlanks Logo Icon CodeBlanks

Summary - Mocking

Combine Mock, patch and side_effect to write a service test.

Summary - Mocking

This group covered the tools of unittest.mock. Mock produces fakes; patch swaps a real object during a test; MagicMock supports magic methods; side_effect gives sequential or exceptional behavior; assert_called_with checks calls.

The final task combines Mock, side_effect and assert_called_with: you'll build a fake service method that returns sequential responses and check the calls.

Practice Mock + side_effect + assert combined

Import Mock from unittest.mock. Create m = Mock(); set m.side_effect = [10, 20]. Print m() and m(). Add the check m.assert_called(); print print("ok").

Starter code

main.py
# import Mock from unittest.mock
# create Mock m; set side_effect [10, 20]
# print m() twice
# assert_called check and print "ok"

Sample solution

main.py
from unittest.mock import Mock

m = Mock()
m.side_effect = [10, 20]
print(m())
print(m())
m.assert_called()
print("ok")

Expected output

10
20
ok

Questions and answers

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

1 What do you use for a Mock that returns different values in sequence?

  • side_effect Correct answer
  • MagicMock
  • return_value
  • patch

Explanation: side_effect cycles a list or calls a function.

2 Summary: call check

Question
m = Mock()
m(7)
m.____(7)
Answer
m = Mock()
m(7)
m.assert_called_with(7)

Explanation: m.assert_called_with(7) checks the call argument.

3 Match the group tools

Term Meaning
Mock Fake object
patch Swaps real
MagicMock Magic methods
side_effect Sequential/exception

All lessons in Advanced