Europe/Paris
Posts

Testing external APIs in Symfony without lying: MockHttpClient, HAR replay and a nightly contract test

November 23, 2026 · 5 min de lecture
A service that calls an external API is badly served by hand-written mocks: the test validates the response you imagined, not the one the provider sends. With Symfony's HttpClient component, you can build three levels of tests that stay fast without lying: simulated responses, replayed real responses, and a contract checked every night. Imen Ezzine (SensioLabs) is presenting "Beyond Mocks" at SymfonyCon Warsaw on November 26 and 27. The abstract published on the Symfony blog starts from a diagnosis many test suites share: "too many mocks, fragile fixtures, outdated assumptions". The announced leads: control HTTP responses, record and replay real interactions, and check that the application still respects the external API's contract. The talk has not happened yet; here is how to apply those three ideas with what the component already provides. A shipping cost calculation that queries a carrier's API (a fictional example). The HTTP client is a scoped client (a client preconfigured with a base URL and headers, injected by name):
Yaml
# config/packages/framework.yaml
framework:
    http_client:
        scoped_clients:
            carrier.client:
                base_uri: '%env(CARRIER_API_URL)%'
                auth_bearer: '%env(CARRIER_API_TOKEN)%'
Php
<?php

declare(strict_types=1);

namespace App\Shipping;

use Symfony\Contracts\HttpClient\HttpClientInterface;

final class CarrierRateProvider
{
    // the argument name selects the carrier.client scoped client
    public function __construct(
        private readonly HttpClientInterface $carrierClient,
    ) {
    }

    public function cheapestRateInCents(string $postcode, int $weightInGrams): int
    {
        $response = $this->carrierClient->request('POST', '/v2/rates', [
            'json' => ['postcode' => $postcode, 'weight_g' => $weightInGrams],
        ]);

        $rates = $response->toArray()['rates'] ?? [];

        if ([] === $rates) {
            throw new NoRateAvailable($postcode);
        }

        return min(array_column($rates, 'amount_cents'));
    }
}
The service depends on HttpClientInterface, not on an implementation. That is what lets the tests hand it a fake client. MockHttpClient implements the same interface as the real client and returns the responses you give it, with no network. JsonMockResponse (Symfony 6.3+) encodes the body as JSON and sets the right content-type. The often-forgotten part: the mock response keeps track of the request it received, so you can check what the service sends, not only what it does with the result.
Php
<?php

declare(strict_types=1);

namespace App\Tests\Shipping;

use App\Shipping\CarrierRateProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;

final class CarrierRateProviderTest extends TestCase
{
    public function testItSendsTheParcelAndReturnsTheCheapestRate(): void
    {
        $mockResponse = new JsonMockResponse(['rates' => [
            ['service' => 'express', 'amount_cents' => 1290],
            ['service' => 'standard', 'amount_cents' => 590],
        ]]);
        $client = new MockHttpClient($mockResponse, 'https://api.carrier.test');

        $rate = (new CarrierRateProvider($client))->cheapestRateInCents('75011', 1200);

        self::assertSame(590, $rate);
        self::assertSame('POST', $mockResponse->getRequestMethod());
        self::assertSame('https://api.carrier.test/v2/rates', $mockResponse->getRequestUrl());
        self::assertSame(
            '{"postcode":"75011","weight_g":1200}',
            $mockResponse->getRequestOptions()['body'],
        );
        self::assertSame(1, $client->getRequestsCount());
    }
}
The json option has already been turned into a string when you read getRequestOptions()['body'], hence the comparison with raw JSON. Error cases are tested the same way: new MockResponse('', ['http_code' => 503]) makes toArray() throw a ServerException, and new MockResponse(info: ['error' => 'host unreachable']) simulates a network failure through a TransportException. When a service chains several calls, you pass MockHttpClient a list of callbacks, one per expected request, each running its assertions before returning its response. Grégoire Pineau described this technique on the JoliCode blog back in 2021, generating the callbacks with a PHP generator. The limit of this level: you wrote the response JSON yourself. A HAR file (HTTP Archive, a standard JSON format holding requests and their full responses) can be exported from a browser's network tab or from some HTTP clients such as Insomnia. Since Symfony 6.4, HarFileResponseFactory turns it into a response source for MockHttpClient. The class is authored by Gary Pegeot, who presented this record-and-replay approach at SymfonyOnline in January 2024. Call the carrier's sandbox (its test environment) once, export the exchange to tests/fixtures/http/carrier_rates.har, then give MockHttpClient the same base URL as the one recorded in the archive (here the sandbox is assumed to be https://api.carrier.test):
Php
// use Symfony\Component\HttpClient\Test\HarFileResponseFactory;

public function testItReadsARecordedCarrierResponse(): void
{
    $factory = new HarFileResponseFactory(__DIR__.'/../fixtures/http/carrier_rates.har');
    $client = new MockHttpClient($factory, 'https://api.carrier.test');

    self::assertSame(590, (new CarrierRateProvider($client))->cheapestRateInCents('75011', 1200));
}
The factory looks for the archive entry whose method, URL and body match the request. With no match, it throws a TransportException naming the missing request. For functional tests, Symfony 8.1 accepts mock_response_factory per scoped client, so you no longer mock every client of the application at once:
Yaml
# config/packages/framework.yaml
when@test:
    framework:
        http_client:
            scoped_clients:
                carrier.client:
                    mock_response_factory: app.test.carrier_har

    services:
        app.test.carrier_har:
            class: Symfony\Component\HttpClient\Test\HarFileResponseFactory
            arguments: ['%kernel.project_dir%/tests/fixtures/http/carrier_rates.har']
CARRIER_API_URL in .env.test must be that same URL, or no entry will match. Before 8.1, the option only exists globally (framework.http_client.mock_response_factory) and applies to every client. An archive recorded in November says nothing about the day the carrier renames amount_cents. That is the job of a contract test (a test that checks the real API still provides what your code consumes). The trick: one assertion function, applied to both the fixture (the recorded test data file, here the HAR) and the live response. If it passes on both, the fixture is still representative.
Php
<?php

declare(strict_types=1);

namespace App\Tests\Contract;

use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\HttpClient;

#[Group('contract')]
final class CarrierContractTest extends TestCase
{
    public function testRecordedAndLiveResponsesExposeWhatWeRead(): void
    {
        $url = getenv('CARRIER_SANDBOX_URL');
        $token = getenv('CARRIER_SANDBOX_TOKEN');
        if (!$url || !$token) {
            self::markTestSkipped('Carrier sandbox credentials are not set.');
        }

        // one entry, body not base64-encoded
        $har = json_decode((string) file_get_contents(__DIR__.'/../fixtures/http/carrier_rates.har'), true, flags: \JSON_THROW_ON_ERROR);
        $recorded = json_decode($har['log']['entries'][0]['response']['content']['text'], true, flags: \JSON_THROW_ON_ERROR);

        $live = HttpClient::createForBaseUri($url, ['auth_bearer' => $token])
            ->request('POST', '/v2/rates', ['json' => ['postcode' => '75011', 'weight_g' => 1200]])
            ->toArray();

        self::assertRatesPayload($recorded);
        self::assertRatesPayload($live);
    }

    /** Only the fields CarrierRateProvider reads. */
    private static function assertRatesPayload(array $payload): void
    {
        self::assertIsList($payload['rates'] ?? null);
        self::assertNotEmpty($payload['rates']);
        foreach ($payload['rates'] as $rate) {
            self::assertIsInt($rate['amount_cents'] ?? null);
        }
    }
}
You only check what the code reads: a new field on the provider side breaks nothing, a removed or retyped field fails the test. Without credentials the test is skipped, so the regular CI stays off the network. The credentials only exist in a scheduled workflow:
Yaml
# .github/workflows/contract.yaml
name: Contract tests
on:
  schedule:
    - cron: '17 4 * * *'
  workflow_dispatch:

jobs:
  contract:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.4'
      - run: composer install --no-progress --prefer-dist
      - run: vendor/bin/phpunit --group contract
        env:
          CARRIER_SANDBOX_URL: ${{ secrets.CARRIER_SANDBOX_URL }}
          CARRIER_SANDBOX_TOKEN: ${{ secrets.CARRIER_SANDBOX_TOKEN }}
A nightly failure blocks no pull request; it signals that the fixture needs re-recording and the code needs adapting. For what should block a merge, see what a green CI should mean.
  • A HAR exported from a browser contains cookies and the Authorization header. Clean the archive before committing it, and drop the entries you do not need.
  • Body matching is a strict string comparison. Re-indented JSON, or keys in a different order from what json_encode produces, will not match, and neither will a body containing a generated date or UUID.
  • A provider's sandbox is not production: rate limits, fake data, sometimes an API version ahead or behind. The contract test catches format drift, not different business behavior in production.
On this page
Book a call