Testing integrations properly: success cases, failures and retries
An integration that works in the success case is only half tested. This article shows which cases belong in the test suite, how to reproduce them with PHPUnit without a real remote system, and where tests end and monitoring has to take over.
What you will learn
The answer first
An integration needs tests for every outcome a request can have: accepted, rejected on business grounds, unauthorised, rate-limited, failed on the remote side, no response at all, and an unexpected response. On top of that come tests for what happens next: is it retried, how often, with which key, and when does the client give up. In unit tests, a test double replaces the HTTP connection so that each of these cases can be produced deliberately. Whether your assumptions about the remote side are correct is shown by recorded real responses and by tests in the provider’s sandbox. Whatever still goes wrong after that has to be reported by monitoring in production.
The general principles (a test needs a concrete expectation and a counter-check) are explained in why software tests need concrete failure cases. This article covers what integrations add on top.
The cases an integration needs
| Case | Typical response | Expected behaviour |
|---|---|---|
| Success | 200, 201, 204 | read the response correctly, store the remote identifier |
| Business rejection | 400, 422 | do not retry; put the reason into follow-up work |
| Not authorised | 401, 403 | do not retry; alert someone, as an expired credential is often the cause |
| Too many requests | 429 | wait, where given for as long as Retry-After says, then retry |
| Remote failure | 500, 502, 503, 504 | retry a limited number of times at increasing intervals |
| Timeout | none | outcome unknown: retry with the same idempotency key or query the state |
| Unexpected response | e.g. an HTML error page instead of JSON, a missing field | a clear error at this point rather than a knock-on error three steps later |
| Duplicate delivery (incoming) | — | no second effect |
The most important distinction lies between rows two and five: a business rejection does not change when you retry; a remote failure often does. Why this distinction is the key design decision is explained in our article on failed automations. The timeout is the trickiest case, because nobody knows whether the remote side has already created the order. Without an idempotency key, a retry can then create a second one.
Making the connection replaceable
To produce a failure on demand, the client must not open the HTTP connection itself. It receives it from outside through an interface. In production, a real HTTP client sits behind it; in tests, a test double. The following example is deliberately small; the error rules are those from the table.
<?php
declare(strict_types=1);
interface Transport
{
/** @return array{status: int, body: string} @throws TransportTimeout */
public function post(string $path, string $body, array $headers): array;
}
final class TransportTimeout extends RuntimeException {}
final class OrderRejected extends RuntimeException {}
final class ServiceUnavailable extends RuntimeException {}
final class OrderClient
{
public function __construct(private Transport $transport, private int $maxAttempts = 3) {}
public function send(array $order, string $idempotencyKey): string
{
$body = json_encode($order, JSON_THROW_ON_ERROR);
for ($attempt = 1; ; $attempt++) {
try {
$r = $this->transport->post('/orders', $body, ['Idempotency-Key' => $idempotencyKey]);
} catch (TransportTimeout) {
$r = null; // outcome unknown: retry with same key
}
if ($r !== null && $r['status'] < 300) {
return json_decode($r['body'], true)['order_id'];
}
if ($r !== null && $r['status'] >= 400 && $r['status'] < 500 && $r['status'] !== 429) {
throw new OrderRejected($r['body']); // our data is wrong: retrying won't help
}
if ($attempt >= $this->maxAttempts) {
throw new ServiceUnavailable("gave up after $attempt attempts");
}
}
}
}OrderRejected. Remote failures, 429 and timeouts are retried up to the limit, always with the same key.In real code there is a pause between attempts, and for 429 the value from Retry-After. It is left out here to keep the example short. If you add it, inject the waiting through an interface as well, so tests do not actually have to wait.
The tests that go with it
For sequences with several responses in a row, a small hand-written double is often easier to read than a configured one. It plays back prepared responses and records every request:
/** Hand-written fake: plays back prepared answers and records every request. */
final class ScriptedTransport implements Transport
{
public array $requests = [];
public function __construct(private array $script) {}
public function post(string $path, string $body, array $headers): array
{
$this->requests[] = $headers;
$next = array_shift($this->script);
if ($next instanceof Throwable) {
throw $next;
}
return $next;
}
}OrderClientTest.php: a prepared exception is thrown; anything else is returned as a response.final class OrderClientTest extends TestCase
{
public function testServerErrorIsRetriedWithTheSameKey(): void
{
$fake = new ScriptedTransport([
['status' => 503, 'body' => ''],
new TransportTimeout(),
['status' => 201, 'body' => '{"order_id":"A-17"}'],
]);
self::assertSame('A-17', (new OrderClient($fake))->send(['sku' => 'X1'], 'key-1'));
self::assertCount(3, $fake->requests);
self::assertSame(['key-1'], array_unique(array_column($fake->requests, 'Idempotency-Key')));
}
public function testValidationErrorIsNotRetried(): void
{
$rejected = ['status' => 422, 'body' => '{"field":"sku"}'];
$fake = new ScriptedTransport([$rejected]);
try {
(new OrderClient($fake))->send(['sku' => ''], 'key-2');
self::fail('expected OrderRejected');
} catch (OrderRejected) {
self::assertCount(1, $fake->requests);
}
}
public function testPermanentTimeoutStopsAfterThreeAttempts(): void
{
$stub = $this->createStub(Transport::class);
$stub->method('post')->willThrowException(new TransportTimeout());
$this->expectException(ServiceUnavailable::class);
(new OrderClient($stub))->send(['sku' => 'X1'], 'key-3');
}
}OK (3 tests, 5 assertions) on PHP 8.3, 8.4 and 8.5.The first test checks not only the result but also that all three requests carried the same key. That very check is missing from many test suites, and that very fault later produces duplicate orders. The third test uses a PHPUnit stub: createStub() returns a double that only answers. If instead you want to verify how often and with what it was called, use createMock() with expects().
The counter-check belongs here too: in a copy, we disabled the condition for 4xx responses. After that, testValidationErrorIsNotRetried failed while the other two stayed green, so the test catches exactly the fault it was written for.
Contracts and recorded responses
A test double contains your assumptions about the remote side. If they are wrong, the tests are green and production is red. Two things help:
Recordings go stale. At the latest when the provider announces a new version, record them again and compare them with the old ones.
A hypothetical example
Green in testing, silent in production
A provider moves its API to a new version. Instead of order_id, the response now contains id. The test doubles keep returning the old field, and every test stays green. In production, the client reads an empty order number and stores it, and only days later does anyone notice that queries about these orders cannot be matched up.
Three measures would have shown this earlier: a recorded response from the new version in the tests, a check in the client that treats a missing order number as an error instead of storing it, and monitoring that reports when no complete transfer succeeds any more.
The provider’s sandbox
Many providers offer a test environment, often called a sandbox. It is the right place for everything a double cannot prove: real authentication, real formats, real error messages for invalid data. But it does not behave like production in every respect. One example from Stripe’s documentation: in live mode, webhooks are retried for up to three days; in a sandbox, three times over a few hours. A test that observes “after three attempts it goes quiet” there describes production wrongly.
A proven split: failure cases and retry logic in fast tests with doubles that run on every change. The success path, authentication and a few rejections in the sandbox, less often and with separate credentials that never match the production ones. Incoming webhooks belong there too: deliver the same message twice and in the wrong order. Why is explained in preventing duplicate processing of webhooks.
After testing: monitoring in production
No test suite notices that a credential at the provider has expired, or that no order has been transferred since yesterday. That is the job of monitoring, and it is as much part of the integration as the tests:
If you would like an existing integration reviewed against these points, or a new one built, that is part of our API integration work.
Common misconceptions
Further sources
- 6. Test Doubles — PHPUnit 12.4 Manual stubs and mocks, willReturn, willThrowException, expects
- RFC 9110 — HTTP Semantics status codes, Retry-After (section 10.2.3)
- RFC 6585 — Additional HTTP Status Codes status code 429 Too Many Requests
- The Idempotency-Key HTTP Header Field IETF draft, version 08, not yet an RFC
- Receive Stripe events in your webhook endpoint example of differences between sandbox and live mode
Further reading
About the author
Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.
An integration that has to hold up when things go wrong?
Tell us which system your application talks to and what currently happens when there is a fault. Together we will work out which cases should be tested and monitored.