Prompt
How do I test third-party API dependencies without hitting the real service?
Latest observation
Oct 6, 2026
OpenAI APIWeb search: off
A good way to test third-party API dependencies is to avoid calling the real service in most tests and instead test against a controlled substitute.
Common approaches
1) Mock the API client in unit tests
If your code uses a wrapper/client class, mock its methods and return fixed responses.
- Fast
- Reliable
- No network dependency
- Best for testing your own logic
Example idea:
- Your code calls
paymentsClient.charge(...) - In the test, replace it with a mock that returns a fake success or throws an error
2) Use a local stub or fake server
Run a lightweight server that imitates the third-party API.
- Useful when you want to verify request/response shape
- Better than mocks for higher-confidence integration tests
- Can simulate success, failure, timeouts, rate limits, etc.
Tools depend on stack, for example:
- WireMock
- MockServer
- MSW for browser/frontend tests
- pytest-httpserver
- nock for Node.js HTTP interception
3) Record/replay HTTP interactions
Capture real API responses once, then replay them in tests.
- Good for APIs that are hard to emulate
- Can be brittle if API responses change
- Make sure to sanitize secrets and PII
Examples:
- VCR.py
- Betamax
- Polly.js
4) Contract testing
Define expected request/response contracts between your app and the API.
- Ensures your code sends what the API expects
- Useful for third-party APIs with stable schemas
- You can combine with mocks/stubs
5) Separate test modes
Have:
- Unit tests with mocks/fakes
- Integration tests against a stub/local emulator
- A small number of end-to-end tests that hit the real API only in a controlled environment
Practical recommendations
- Put API access behind a thin wrapper interface.
- Make your code depend on that interface, not directly on HTTP calls.
- In tests, inject a fake/mock implementation.
- Only use the real service in a few smoke tests, and run them separately.
Good things to test with a fake
- Successful response
- Auth failure
- Validation error
- Rate limit error
- Timeout / network failure
- Malformed response
- Retries and backoff logic
Rule of thumb
- Mock for logic
- Stub for request/response behavior
- Real service only for limited smoke tests
If you tell me your language/framework, I can show a concrete example.