How would you test code that calls an external payment API?
Answer
- Hide the provider behind your own interface (
PaymentGateway) and inject it. - Unit tests: use a fake or mock of your interface; cover success, card declined, timeout, duplicate request.
- Adapter tests: stub HTTP with
responses/respx or recorded responses; check the request format and how errors are mapped. - A few integration tests against the provider's sandbox/test mode (often nightly).
- Test idempotency keys and webhook signature checks.
- Never call the real production API from tests.
Practice this question in Repaso