Why is mocking HTTP calls important in unit tests, and what problem does it solve compared to calling the real API?
Answer
Calling a real external API from a unit test makes the test slow, flaky (it can fail due to network issues or the third party's downtime rather than a real bug), and dependent on external state that the test author does not control, such as rate limits or data that changes over time. Mocking the HTTP layer — using `unittest.mock.patch` on the calling code, or a library like `responses`/`requests-mock` that intercepts `requests` calls at the transport level — lets a test assert exactly how the code under test behaves for a given, controlled response, including edge cases like a 500 error or a timeout, that would be difficult or unsafe to trigger against a real service on demand.
Strong answer includes
- real API calls make tests slow, flaky, and dependent on uncontrolled external state
- mocking intercepts the HTTP layer to return a controlled, predetermined response
- lets tests reliably exercise edge cases like errors or timeouts on demand
Practical example
responses.add(responses.GET, "https://api.example.com/user", json={"id": 1}, status=200)lets a test verify the code's behavior for a successful response and, in another test, for a simulated
status=503, without ever hitting the real API.