Lesson 7 of 9 · 23m
Testing External Services Without Believing Your Own Mocks
Adapter tests, PSR-18 fakes, recorded contracts, consumer-driven expectations, and the thin slice of live smoke testing that catches drift.
The classic external-service failure is a perfectly green suite and a broken production deploy. Every test mocked the API client. The vendor changed one field name, and nobody noticed until customers did. The fix is not to hit production APIs from every test. The fix is layered confidence.
Wrap the vendor behind an adapter
Your application should depend on a small interface shaped by your use case:
interface IssueTracker
{
public function createIssue(string $title, string $body): string;
}The GitHub adapter implementation knows about endpoints, authentication headers, pagination, and response shape. Application unit tests mock IssueTracker. Adapter integration tests verify the translation layer.
Fake transport is still a real client test
For a PSR-18 client, you can test serialization and response handling without network I/O by injecting a fake transport:
final class RecordingClient implements ClientInterface
{
public array $requests = [];
public function sendRequest(RequestInterface $request): ResponseInterface
{
$this->requests[] = $request;
return new Response(201, ['Content-Type' => 'application/json'], '{"id":42,"state":"open"}');
}
}Now you can assert the path, headers, JSON body, error handling, and timeouts. This does not prove GitHub behaves that way, but it proves your adapter does what you intended.
Use contract tests for the vendor's shape
A contract fixture is a real captured response, committed to the repository:
{"id": 42, "number": 42, "state": "open", "html_url": "https://github.com/acme/widgets/issues/42"}The adapter test consumes it and proves the fields you depend on are parsed correctly. When the integration breaks in production, compare the real response with the fixture and update the contract intentionally.
For larger systems, tools like WireMock or Pact formalize this. Do not adopt the tooling before you adopt the habit: know exactly which response fields are contractual for you.
Reserve live tests for smoke, not correctness
A nightly live test can create or read a harmless resource in a sandbox account. It catches credential expiry, endpoint drift, TLS issues, and vendor behavior changes. It should not gate every pull request. Vendors rate-limit, networks flake, and CI becomes non-deterministic for reasons unrelated to your code.
Field notes
- Never record Authorization headers or customer data in contract fixtures.
- Test error paths: 401, 403, 409, 422, and 500 have different operational meanings.
- Timeouts are behavior — assert explicit connect and read timeouts. A vendor SDK mock is a hypothesis; an adapter test plus a contract is evidence.
Was this lesson helpful?