QA
Intermediate LevelPython

How do you mock external API requests and database calls in tests using unittest.mock.patch and MagicMock?

❓ Interview Prompt: Explain `unittest.mock`, `MagicMock`, `@patch` decorator, mocking external API HTTP calls, and verifying call arguments.

'unittest.mock' allows replacing real external dependencies (HTTP APIs, databases) with 'MagicMock' objects during unit testing:

The 'patch()' Decorator:

Intercepts imports at execution time, ensuring tests run isolated without executing actual network calls!

Code Implementation Example

python
from unittest.mock import patch, MagicMock
import requests

def fetch_user_email(user_id):
    resp = requests.get(f'https://api.example.com/users/{user_id}')
    return resp.json()['email']

@patch('requests.get')
def test_fetch_user_email(mock_get):
    # Configure mock return value
    mock_response = MagicMock()
    mock_response.json.return_value = {'email': 'test@example.com'}
    mock_get.return_value = mock_response
    
    email = fetch_user_email(101)
    assert email == 'test@example.com'
    mock_get.assert_called_once_with('https://api.example.com/users/101')
💡Mocking HTTP API requests using unittest.mock.patch.
🎯 Interview Key Takeaway

Use unittest.mock.patch to isolate unit tests from external HTTP network APIs and database calls.

#unittest.mock#patch#MagicMock#Testing#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?