Sobes.tech
Junior — Middle

What are the ways to use mock objects in testing?

sobes.tech AI

Answer from AI

Mock objects are used to imitate the behavior of real objects in tests, in order to isolate the tested code from external dependencies.

Main usage methods:

  • Dependency substitution: replacing real objects (e.g., databases, APIs) with mocks to make tests fast and predictable.
  • Call verification: using mocks to check whether certain methods were called, with what arguments, and how many times.
  • Behavior configuration: mocks allow setting return values or thrown exceptions to test different scenarios.

In Python, the unittest.mock module is often used for this:

from unittest.mock import Mock

# Create a mock
mock_obj = Mock()

# Configure return value
mock_obj.method.return_value = 42

# Use the mock
result = mock_obj.method()
print(result)  # 42

# Verify the call
mock_obj.method.assert_called_once()