The diagnosis
The service under test
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'));
}
}
Level 1: MockHttpClient and assertions on the request
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());
}
}
Level 2: replaying real responses from a HAR file
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));
}
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']
Level 3: checking that the contract still holds
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);
}
}
}
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 }}
The traps
- 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.
Sources
- SymfonyCon Warsaw 2026: Beyond Mocks — Symfony Blog, Mélyne Freuze, November 11, 2026 (talk by Imen Ezzine, SensioLabs)
- Testing with HttpClient, the automatic way — SymfonyOnline, Gary Pegeot, January 2024
- Symfony HttpClient and sequential requests assertions — JoliCode Blog, Grégoire Pineau, September 15, 2021
- HTTP Client, Testing section — Symfony documentation
- HttpClient component CHANGELOG — JsonMockResponse (6.3), HarFileResponseFactory (6.4)
- FrameworkBundle CHANGELOG — per-scoped-client mock_response_factory (8.1)