Junior — Middle
Is it possible to use mocks to evaluate API functionality during testing?
sobes.tech AI
Answer from AI
Yes, mocks are widely used to evaluate API functionality during testing. They allow isolating the tested component by replacing real dependencies (such as external services or databases) with simulations that return predictable responses. This helps verify the API's logic without interacting with real services, speeding up testing and making it more stable.
Example of using mocks:
import requests
from unittest.mock import patch
def get_user_data(user_id):
response = requests.get(f'https://api.example.com/users/{user_id}')
return response.json()
# In a test
@patch('requests.get')
def test_get_user_data(mock_get):
mock_get.return_value.json.return_value = {'id': 1, 'name': 'Test User'}
data = get_user_data(1)
assert data['name'] == 'Test User'
Thus, mocks help verify how the API processes data without depending on a real server.