CodeBlanks Logo Icon CodeBlanks

unittest.mock

Learn mock objects with unittest.mock.Mock.

unittest.mock

unittest.mock is Python's built-in mocking library. It produces fake objects that replace real ones; tests then run free of external dependencies.

The most basic class is Mock. You create a fake object with Mock(); any attribute or method call on it returns another Mock by default.

from unittest.mock import Mock

m = Mock()
m.method.return_value = 42
print(m.method())  # 42

With return_value you decide what a call returns. This is the simplest way to mimic behavior without hitting a real service.

Behavior with return_value

You set what a Mock returns for a call with return_value. It can be a fixed value, a function or another Mock.

Example: m = Mock(); m.return_value = 5. Then calling m() returns 5. For methods, write m.fetch.return_value = data; calling m.fetch() gives data.

Calling it multiple times returns the same value each time. You check the call count with m.call_count and the call arguments with m.call_args.

Practice Mock with a fake method

Import Mock from unittest.mock. Create m = Mock(); set m.fetch.return_value = 42. Call print(m.fetch()).

Starter code

main.py
# import Mock from unittest.mock
# create Mock m; set fetch method return value to 42
# print the result of fetch()

Sample solution

main.py
from unittest.mock import Mock

m = Mock()
m.fetch.return_value = 42
print(m.fetch())

Expected output

42

Questions and answers

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

1 What does Mock().method() return by default?

  • It raises an error
  • None
  • A new Mock object Correct answer
  • The called method name

Explanation: A call on a Mock returns a new Mock by default.

2 Import Mock

Question
from unittest.mock import ____

m = Mock()
m.method.return_value = 42
Answer
from unittest.mock import Mock

m = Mock()
m.method.return_value = 42

Explanation: The Mock class comes from the unittest.mock module.

3 Match the Mock pieces

Term Meaning
Mock() Fake object
return_value Return value
call_count Call count
call_args Call arguments

All lessons in Advanced