Skip to content

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.

  • Who it is forDevelopers, technical project leads
  • LevelHow-to
  • Reading timeabout 10 minutes
  • Last updated24 October 2026

What you will learn

  • Which cases an integration needs beyond the success case
  • How a test double for the HTTP connection produces failures on demand
  • How to check that retries use the same idempotency key
  • What recorded responses, the provider’s sandbox and production monitoring are for

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

Outcomes of a request and what the test should establish; status codes per RFC 9110, 429 per RFC 6585
CaseTypical responseExpected behaviour
Success200, 201, 204read the response correctly, store the remote identifier
Business rejection400, 422do not retry; put the reason into follow-up work
Not authorised401, 403do not retry; alert someone, as an expired credential is often the cause
Too many requests429wait, where given for as long as Retry-After says, then retry
Remote failure500, 502, 503, 504retry a limited number of times at increasing intervals
Timeoutnoneoutcome unknown: retry with the same idempotency key or query the state
Unexpected responsee.g. an HTML error page instead of JSON, a missing fielda 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.

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI
<?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");
            }
        }
    }
}
A success returns the order number. A 4xx response other than 429 leads straight to 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:

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, PHPUnit 10.5
/** 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;
    }
}
Excerpt from OrderClientTest.php: a prepared exception is thrown; anything else is returned as a response.
PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, PHPUnit 10.5
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');
    }
}
Result: 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:

  • Recorded responses. Real responses from the provider’s sandbox are stored as files and read in the tests, including error responses as far as they can be provoked. Personal data and credentials are removed first.
  • A checked contract. If there is a machine-readable description of the API, for example in OpenAPI format, requests and recorded responses can be validated against it. If there is none, it is worth writing one yourself, as described in integrating an API with insufficient documentation.

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:

  • Share of successful and failed requests, split into 4xx and 5xx; a rise in 4xx points to a change on your side or the provider’s.
  • Response times, because timeouts are often preceded by responses that keep getting slower.
  • Age of the oldest item not yet transferred, and an alert when an expected transfer does not happen.
  • Log entries with reference code and idempotency key, so that a complaint can be matched to a request.

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

Most problems in production arise in the other cases: timeouts, rejections, retries. Without a test double, those are rarely tested.

They prove that the parts work together, but you cannot order a timeout or a 503 from them; they are slow and can create real data. They complement fast tests rather than replacing them.

It only proves that your code can handle your assumption. Whether the assumption is right is shown by recorded real responses.

Further sources

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.