Mocking External Services with unittest.mock
1Concept
`unittest.mock` replaces external dependencies (HTTP APIs, databases) with `Mock` or `MagicMock` objects. `@patch` intercepts imports, preventing external network calls during unit testing.
2Architecture Diagram
@patch('requests.get') ---> Replaces requests.get with MagicMock returning mock response3Code Example
Python 3.12
from unittest.mock import MagicMock
# Create mock payment service
mock_payment_gateway = MagicMock()
mock_payment_gateway.charge.return_value = {"status": "SUCCESS", "tx_id": "TX-9912"}
response = mock_payment_gateway.charge(amount=500.0)
print(f"Mocked Response: {response}")
# Verify call assertions
mock_payment_gateway.charge.assert_called_once_with(amount=500.0)
print("Assertion verified: mock_payment_gateway.charge was called exactly once with $500.0")4Expected Output
Mocked Response: {'status': 'SUCCESS', 'tx_id': 'TX-9912'}
Assertion verified: mock_payment_gateway.charge was called exactly once with $500.05Key Takeaways
- ✓`mock.assert_called_once_with(...)` verifies arguments passed to dependencies.
- ✓Always patch where the object is LOOKED UP, not where it is defined.
- ✓Use `side_effect = Exception(...)` to simulate network errors and timeouts.