Sobes.tech
Junior — Middle

What is the purpose of mock objects in automated testing?

sobes.tech AI

Answer from AI

Mock objects are used in automated testing to simulate the behavior of real components with which the tested code interacts.

The main purposes of mock objects:

  • Isolate the tested module from external dependencies (e.g., databases, network services).
  • Control the behavior of dependencies to test the code's reactions to different scenarios.
  • Speed up test execution by avoiding real calls to slow or unreliable resources.

Example in Python using the unittest.mock library:

from unittest.mock import Mock

def fetch_data(api_client):
    response = api_client.get('/data')
    return response.json()

# In the test, create a mock object api_client
mock_api_client = Mock()
mock_api_client.get.return_value.json.return_value = {'key': 'value'}

result = fetch_data(mock_api_client)
assert result == {'key': 'value'}

Thus, mock objects allow testing logic without dependence on real external services.