Junior — Middle
Explain the concept of Mock objects and how they are used in software testing
sobes.tech AI
Answer from AI
Mock objects are special stubs that imitate the behavior of real objects in tests. They are used to isolate the code being tested from external dependencies (such as databases, network services).
Goals of using Mock objects:
- To verify how the code interacts with dependencies
- To avoid side effects and long execution times
- To control the return values and states of dependencies
In Python, the unittest.mock module is often used to create mock objects.
Example:
from unittest.mock import Mock
def fetch_data(api_client):
response = api_client.get('/data')
return response.json()
# Test
mock_api = Mock()
mock_api.get.return_value.json.return_value = {'key': 'value'}
result = fetch_data(mock_api)
assert result == {'key': 'value'}
Here, mock_api simulates a real API client, allowing testing of the fetch_data function without an actual network request.