Junior — Middle
Do you use mock objects when writing automated tests?
sobes.tech AI
Answer from AI
Yes, mock objects are widely used in writing automated tests, especially to isolate the tested code from external dependencies such as databases, network requests, or third-party services. This allows testing the logic of components without the need for real interaction with external systems.
In Python, the unittest.mock module is often used to create mock objects.
Example of using a mock object:
from unittest.mock import Mock
def fetch_data(api_client):
response = api_client.get('/data')
return response.json()
# In a test
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 controlling the behavior of dependencies and writing more reliable and faster tests.