SymfonyCon Warsaw 2026, November 26 - 27

Beyond Mocks

Imen Ezzine

● REC   ▶ PLAY
Imen Ezzine speaking at a conference

Imen EZZINE

PHP Symfony Developer

  • YouTube Café Tech avec Imen
  • Symfony mascot with the Tunisian flag Symfony community in Tunisia
  • LinkedIn Imen Ezzine
  • Medium @imenezzine
SensioLabs, creator of Symfony

Side A · Part 1

The problem

The “This is fine” dog drinks its coffee in a room on fire

Your application does not live alone

Payment

Create a payment, issue a refund

CRM

Sync contacts, leads, opportunities

ERP

Stock, orders, invoices

AI

A prompt in, and never the same answer twice

And every one of these features deserves tests.

Two options… neither is great

Real HTTP callsHandwritten mocks
RealismReal responsesWhat we imagine the API returns
SpeedSlow (network)Instant
Stability in CIDepends on the provider (quotas, outages)Stable
CostPaying APIs bill every call (OpenAI, payments…)Free
SecretsAPI keys in CINone
MaintenanceNone… as long as the API answersTedious, and it drifts

The handwritten mock


$client = new MockHttpClient([
    new MockResponse(
        json_encode([
            'id' => 'pay_123',
            'status' => 'succeeded',
            'amount' => 4200,
            'currency' => 'eur',
            // ... and the 40 other fields of the real response?
        ]),
        ['response_headers' => ['content-type' => 'application/json']],
    ),
]);

$service = new PaymentService($client);
    

Tedious to write, and nothing guarantees it still looks like the API.


class PaymentServiceTest extends TestCase
{
    private const API = 'https://api.payment.example.com/v1';

    public function testPaymentRequiringAuthenticationThenPartialRefund(): void
    {
        $client = new MockHttpClient([
            function (string $method, string $url, array $options): MockResponse {
                $this->assertSame('POST', $method);
                $this->assertSame(self::API.'/customers', $url);
                $this->assertSame('email=jane%40example.com&name=Jane+Doe&metadata%5Border_id%5D=1337', $options['body']);
                $this->assertSame('Authorization: Bearer sk_test_123', $options['normalized_headers']['authorization'][0]);
                $this->assertSame('Idempotency-Key: order-1337-customer', $options['normalized_headers']['idempotency-key'][0]);

                return new MockResponse(json_encode([
                    'id' => 'cus_123', 'object' => 'customer', 'created' => 1760000000, 'email' => 'jane@example.com', 'name' => 'Jane Doe',
                    'balance' => 0, 'currency' => null, 'default_source' => null, 'delinquent' => false, 'description' => null, 'discount' => null,
                    'invoice_prefix' => 'A1B2C3', 'invoice_settings' => ['custom_fields' => null, 'default_payment_method' => null, 'footer' => null],
                    'livemode' => false, 'metadata' => ['order_id' => '1337'], 'phone' => null, 'preferred_locales' => [], 'shipping' => null, 'tax_exempt' => 'none',
                ]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_1']]);
            },
            function (string $method, string $url, array $options): MockResponse {
                $this->assertSame('POST', $method);
                $this->assertSame(self::API.'/payment_intents', $url);
                $this->assertSame('amount=4200&currency=eur&customer=cus_123&payment_method=pm_card_3ds&confirm=true&return_url=https%3A%2F%2Fshop.example.com%2Freturn', $options['body']);
                $this->assertSame('Idempotency-Key: order-1337-payment', $options['normalized_headers']['idempotency-key'][0]);

                return new MockResponse(json_encode([
                    'id' => 'pay_123', 'object' => 'payment_intent', 'amount' => 4200, 'amount_capturable' => 0, 'amount_received' => 0, 'currency' => 'eur',
                    'customer' => 'cus_123', 'status' => 'requires_action', 'capture_method' => 'automatic', 'confirmation_method' => 'automatic',
                    'client_secret' => 'pay_123_secret_456', 'created' => 1760000001, 'livemode' => false, 'payment_method' => 'pm_card_3ds',
                    'next_action' => ['type' => 'redirect_to_url', 'redirect_to_url' => ['url' => 'https://hooks.payment.example.com/3ds/pay_123', 'return_url' => 'https://shop.example.com/return']],
                    'payment_method_options' => ['card' => ['request_three_d_secure' => 'automatic', 'installments' => null, 'mandate_options' => null, 'network' => null]],
                    'payment_method_types' => ['card'], 'last_payment_error' => null, 'latest_charge' => null, 'metadata' => [], 'setup_future_usage' => null,
                ]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_2']]);
            },
            function (string $method, string $url, array $options): MockResponse {
                $this->assertSame('GET', $method);
                $this->assertSame(self::API.'/payment_intents/pay_123?expand%5B0%5D=latest_charge', $url);

                return new MockResponse(json_encode([
                    'id' => 'pay_123', 'object' => 'payment_intent', 'amount' => 4200, 'amount_received' => 4200, 'currency' => 'eur', 'status' => 'succeeded',
                    'latest_charge' => [
                        'id' => 'ch_789', 'object' => 'charge', 'amount' => 4200, 'amount_captured' => 4200, 'amount_refunded' => 0, 'captured' => true, 'paid' => true,
                        'balance_transaction' => 'txn_321', 'billing_details' => ['address' => ['city' => 'Paris', 'country' => 'FR', 'line1' => null, 'postal_code' => '75002'], 'email' => 'jane@example.com'],
                        'outcome' => ['network_status' => 'approved_by_network', 'reason' => null, 'risk_level' => 'normal', 'risk_score' => 12, 'seller_message' => 'Payment complete.', 'type' => 'authorized'],
                        'payment_method_details' => ['type' => 'card', 'card' => ['brand' => 'visa', 'country' => 'FR', 'exp_month' => 12, 'exp_year' => 2030, 'funding' => 'credit', 'last4' => '3184',
                            'three_d_secure' => ['authentication_flow' => 'challenge', 'result' => 'authenticated', 'version' => '2.2.0'], 'network' => 'visa']],
                        'receipt_url' => 'https://pay.example.com/receipts/ch_789', 'refunded' => false, 'refunds' => ['object' => 'list', 'data' => [], 'has_more' => false],
                    ],
                    'next_action' => null, 'last_payment_error' => null, 'customer' => 'cus_123', 'livemode' => false, 'metadata' => [],
                ]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_3']]);
            },
            function (string $method, string $url, array $options): MockResponse {
                $this->assertSame('POST', $method);
                $this->assertSame(self::API.'/refunds', $url);
                $this->assertSame('payment_intent=pay_123&amount=1500&reason=requested_by_customer&metadata%5Border_id%5D=1337', $options['body']);

                return new MockResponse(json_encode([
                    'id' => 're_654', 'object' => 'refund', 'amount' => 1500, 'balance_transaction' => 'txn_987', 'charge' => 'ch_789', 'created' => 1760000420,
                    'currency' => 'eur', 'destination_details' => ['type' => 'card', 'card' => ['reference' => '7412589630', 'reference_status' => 'available', 'reference_type' => 'acquirer_reference_number', 'type' => 'refund']],
                    'metadata' => ['order_id' => '1337'], 'payment_intent' => 'pay_123', 'reason' => 'requested_by_customer', 'receipt_number' => null, 'status' => 'succeeded',
                ]), ['http_code' => 200, 'response_headers' => ['content-type' => 'application/json', 'request-id' => 'req_4']]);
            },
            new MockResponse('{"error":{"type":"rate_limit_error","code":"rate_limit","message":"Too many requests, please retry later."}}', ['http_code' => 429, 'response_headers' => ['retry-after' => '1']]),
            new MockResponse('{"object":"list","data":[{"id":"re_654","amount":1500,"status":"succeeded"}],"has_more":false,"url":"/v1/refunds"}', ['http_code' => 200]),
        ]);

        $service = new PaymentService($client, 'sk_test_123', new NullLogger());

        $payment = $service->pay(new Order(1337, 4200, 'eur', new Customer('jane@example.com', 'Jane Doe')), 'pm_card_3ds');
        $this->assertSame('requires_action', $payment->status);
        $this->assertSame('https://hooks.payment.example.com/3ds/pay_123', $payment->redirectUrl);

        $this->assertSame('succeeded', $service->refresh($payment)->status);
        $this->assertSame('succeeded', $service->refund($payment, 1500)->status);
        $this->assertCount(1, $service->refunds($payment));
        $this->assertSame(6, $client->getRequestsCount());
    }
}
    
A man squints to read a tiny piece of paper

The day the API changes its format…

Humorous gif: nobody saw that coming

… your mocks did not notice a thing.

What if we recorded reality?

1. Record

The test makes the real calls once and saves every request / response pair.

2. Commit

The recording lives next to the test and is reviewed in the pull request like code.

3. Replay

Every following run replays the responses, without the network.

The idea is not new: php-vcr has been doing it for years.
Since Symfony 8.2, it is built into HttpClient, with no external dependency.

Record once, replay on every run

RECFirst run: recordPLAYNext runs: replayYour testPHPUnit.harThird-party APIGET200GET200no network call: CI replays the fileHAR: standard, readable, diffable

Three building blocks

HttpClient component

RecorderHttpClient

Decorates the HTTP client: replays, records, or passes through.

PHPUnit Bridge

#[UseRecord]

Tells which HAR file a test uses.

When running the tests

SYMFONY_HTTP_RECORDER

Decides whether to replay or to record.

Side A · Part 2

The solution

“We can pull up the tape”: a man explains that the recording can be played back

HAR: HTTP Archive

The W3C JSON format for archiving HTTP exchanges: readable, reviewed in a pull request like code, opened by browser devtools


{
  "startedDateTime": "2026-09-03T14:07:14.638Z",
  "request": {
    "method": "POST",
    "url": "https://auth.example.com/oauth/token",
    "postData": {
      "text": "grant_type=client_credentials&client_secret=%5BREDACTED%5D"
    }
  },
  "response": {
    "status": 200,
    "headers": [{"name": "content-type", "value": "application/json"}],
    "content": {
      "mimeType": "application/json",
      "text": "{\"access_token\":\"[REDACTED]\",\"expires_in\":3600}"
    }
  }
}
    

Simplified excerpt of a file written by the recorder. A binary body is stored as base64.

Symfony already knew how to… replay


use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Test\HarFileResponseFactory;

$client = new MockHttpClient(new HarFileResponseFactory(__DIR__.'/fixtures/api.har'));
    
  • HarFileResponseFactory already exists in the component
  • But you have to produce the HAR file yourself
  • The recording half was missing

The recorder builds on what is already there: one HAR format, to record and to replay.

RecorderHttpClient

Record and replay, in three steps

Step 1

Register the PHPUnit extension


<!-- phpunit.dist.xml -->
<extensions>
    <bootstrap class="Symfony\Bridge\PhpUnit\SymfonyExtension">
        <!-- optional: all recordings in a single directory -->
        <parameter name="http-recorder-directory" value="tests/records"/>
    </bootstrap>
</extensions>
    

Without the parameter, each .har file lives next to its test. With it, the tree follows the namespace: tests/records/App/Tests/FooTest/testBar.har

Step 2

Add the attribute to the test


use Symfony\Bridge\PhpUnit\Attribute\UseRecord;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class GetRandomControllerTest extends WebTestCase
{
    #[UseRecord]
    public function testRandom(): void
    {
        $client = static::createClient();
        $client->request('GET', '/random');

        $this->assertResponseIsSuccessful();
    }
}
    

The test uses GetRandomControllerTest/testRandom.har, stored next to it. Nothing else changes in the code.

Step 3

Record once

$ SYMFONY_HTTP_RECORDER=missing vendor/bin/phpunit --filter testRandom. 1 / 1 (100%)OK (1 test, 1 assertion)+ tests/Controller/GetRandomControllerTest/testRandom.harreview, then commit
  1. Real calls, GetRandomControllerTest/testRandom.har is written
  2. Review the file, commit it
  3. Next runs and CI: SYMFONY_HTTP_RECORDER=replay (the default when it is not set), replay, zero network

Where does the recorder sit?

Your codeservice, controllerhttp_clientscoped, retry…RecorderHttpClientnewTransportcurl, amp…Third-party APIInnermost decorator of http_client.transport→ sees absolute URLs (after ScopingHttpClient)→ below the decorators: scoped, retry, your options→ a single file for all the clients of the test

Four modes, one default

replaydefault, CI · replays, fails if missing.harAPIGET200missingrecords what is missing · first recording.harAPIGETGET200+ 1 entryrecordrecords everything again · after an API change.harAPIGET200rewrittenpassthroughreal requests, no file · by hand, in dev.harAPIGET200

Fail closed: a committed test never touches the network. Recording is an explicit choice.

Record mode

Your testRecorderHttpClientreal HTTP callThird-party APIthe real response comes back untouchedcopy, on the last chunkDefaultRedactorredacts secretsHarFilewritten under flock()testX.harentry written

Replay mode

Your testRecorderHttpClientDefaultRedactorredacts the requestComparisonmethod, URL, bodytestX.harfoundResponse replayed by MockHttpClientno network callmissingExceptionthe test fails

With SYMFONY_HTTP_RECORDER=missing, a missing entry triggers the real call, which gets recorded.

Pick the tests with PHPUnit


# record a class again after an API change
SYMFONY_HTTP_RECORDER=record vendor/bin/phpunit --filter GetRandomControllerTest

# add what is missing in a group, without touching the rest
SYMFONY_HTTP_RECORDER=missing vendor/bin/phpunit --group payment
    

Why not in the attribute?

A recording mode must never be committed: it is a setting for the duration of a run.

Before committing

Review the diff of the HAR files, like any other code.

CI never touches the network

CIreplayNetwork.harGETstopGET200committed = replayeda forgotten file fails, it never calls out
  • A forgotten file makes the test fail, without any request
  • The code under test catches the exception? A PHPUnit warning still reports the missing request, with its redacted URL
  • Invalid value in SYMFONY_HTTP_RECORDER: a warning, then replay

Side A · Part 3

Under the hood

Cartoon: a mechanic dives under the hood of a car

Redacted by default

Headers

Authorization, Proxy-Authorization, Cookie, Set-Cookie, DPoP, X-Api-Key, X-Auth-Token

Query, forms, JSON

IANA OAuth registry, OpenID Connect, SAML: access_token, refresh_token, id_token, client_secret, SAMLResponse…

Common names

password, secret, token, api_key

code and key: query string and forms only, not in JSON

+ URL fragments and the Location header, handled as URLs. On the request and on the response, before anything is written.

What really goes out… and what is written

Real exchange


POST /oauth/token
Authorization: Basic bXktYXBwOnMzY3IzdA==

grant_type=client_credentials
&client_id=my-app&client_secret=s3cr3t

200 OK
{"access_token":"eyJhbGciOi...",
 "token_type":"Bearer","expires_in":3600}
            

.har file


POST /oauth/token
Authorization: [REDACTED]

grant_type=client_credentials
&client_id=my-app&client_secret=%5BREDACTED%5D

200 OK
{"access_token":"[REDACTED]",
 "token_type":"Bearer","expires_in":3600}
            

Without redaction, all of this would end up in a file the workflow asks you to commit.

Adapt it to your API


http_client:
    recorder:
        # headers, query string, forms and JSON: added to the built-in lists
        redact: ['X-Custom-Secret', 'sig', 'pin']
        # never redacted, removed from the built-in lists
        redact_except: ['code']
        # or replace the redaction entirely
        redactor: ~                 # RedactorInterface service
    

redact_except: when code is not a secret in your tests, and you need it.

A field that changes on every request (timestamp, nonce, request id)? Add it to redact: redacted on both sides, it is also ignored when matching.

Redacting without damaging the response


{"meta":{},"password":"x","n":1.0,"big":12345678901234567890}
    

json_decode + json_encode


{"meta":[],"password":"[REDACTED]","n":1,"big":1.2345678901234567e+19}
        

In-place replacement


{"meta":{},"password":"[REDACTED]","n":1.0,"big":12345678901234567890}
        

The JSON is no longer decoded then re-encoded: sensitive values are replaced in a single pass, the rest is byte-for-byte identical ({}, floats, big integers, escapes, formatting).

Matching

Replaying the right response for the right request

Recognising a request

Method

GET, POST…

URL

Absolute, query string included

Body

When it is a string; a streamed body is not compared

Requests are first normalised the way HttpClient does it: json, query, base_uri, auth_basic, auth_bearer… end up in the recorded URL, body and headers.

Secrets redacted on both sides, and the random boundary of a multipart body replaced with a fixed value.

Redacting on both sides

Request of the test/x?token=secretRedactorRedacted request/x?token=%5BREDACTED%5DEntry of the .har file/x?token=%5BREDACTED%5Dredacted when recordedComparisonidentical

Redaction is deterministic: the real request, with its real secrets, still matches.

Why not store a hash of the real request next to it? A short secret in a query string could still be guessed offline from a committed file.

Same request, different responses


// Recorded: an asynchronous export polled until it is ready
$client->request('GET', 'https://api.example.com/exports/42')->toArray(); // 202
$client->request('GET', 'https://api.example.com/exports/42')->toArray(); // 200

// On replay: 202, then 200, then 200 (the last response is served again)
    
  • Entries are appended in order, never overwritten, and replayed in order
  • The replay cursor belongs to the test, not to the client: it survives the kernel reboot done by KernelBrowser
  • RetryableHttpClient cancels the failed attempt: a 500 then a 200 only records the 200

Side B · Part 4

The pitfalls

Admiral Ackbar in Star Wars: “It's a trap!”

Recording an error response


// Not recorded: the exception consumes the response
$response->getContent();   // ClientException on a 404

// Recorded with its status and its body
$response->getContent(false);
$response->toArray(false);
    

Only fully received responses are written. A response destroyed without being read, cancelled, or consumed through the exception is not recorded: on replay, the test fails clearly instead of receiving an empty body.

What is redacted is replayed redacted


{"access_token":"[REDACTED]","id_token":"[REDACTED]","token_type":"Bearer"}
    
  • A test that verifies the signature of a replayed id_token will fail
  • Solution: redact_except, or your own RedactorInterface
  • And in that case: review the file before committing it

Side B · Part 5

Beyond the recording

500 · timeout · diff

Failures you cannot order


$client = new MockHttpClient([
    // The provider is down
    new JsonMockResponse(['error' => 'unavailable'], ['http_code' => 503]),
    // The provider never answers: an empty chunk is an idle timeout
    new MockResponse((static function () { yield ''; })()),
    // The connection fails before any response
    new MockResponse(info: ['error' => 'Could not resolve host']),
]);

$service = new PaymentService($client);
    

A real API will not give you a 503 or a timeout when you ask for one. Here the handwritten mock is the right tool: the response is short, and it is the scenario itself.

What a replayed test proves

It proves

Your code handles the response as the API sent it on recording day: real fields, real formats, real headers.

It does not prove

That the API still answers that way. If the provider renames a field tomorrow, the replay stays green.

Better than a handwritten mock, but the same blind spot. So we check the contract regularly, by hand, in dev, never in CI.

Real services, by hand, in dev


# on your machine, with sandbox keys, every few weeks
SYMFONY_HTTP_RECORDER=passthrough vendor/bin/phpunit --group third-party
    
  • passthrough: real calls, .har files neither read nor written
  • Red = the provider changed, before production finds out
  • Not in CI: that would bring back everything we removed

Secrets in CI, a bill on every run, failures you do not control, real payments. This check stays a manual step: it does not get automated.

Then refresh, and read the diff


SYMFONY_HTTP_RECORDER=record vendor/bin/phpunit --group third-party
git diff tests/records/
    

   "content": {
     "mimeType": "application/json",
-    "text": "{\"status\":\"succeeded\",\"amount\":4200}"
+    "text": "{\"status\":\"paid\",\"amount\":{\"value\":4200}}"
   }
    

An unchanged exchange keeps its exact place in the file: the diff only shows what the API changed. Review it, adapt the code, commit the new contract.

Side B · Part 6

Behind the scenes

“Let's rewind and try again”: two characters suggest rewinding and starting over

The comment that changed the direction

We do want record and replay in HttpClient […] build on what is already there instead of alongside it.

None of this is a rejection of the idea. It is a request to make the recorder produce real HAR that our existing reader consumes, to fail closed, and to keep secrets out of files people commit. Nicolas Grekas, August 17, 2026

What the review changed

First versionToday
SecretsAuthorization, cookies, tokens written as isRedacted by default, request and response
Missing entryReal network call by default, silentlyException, never the network
stream()Broken, and getContent() serialised the requestsAsyncResponse, recorded chunk after chunk
Optionstimeout: 5 became 60 s when recordingOriginal options passed through as is

Side B · Part 7

Conclusion

Barack Obama waves and leaves the lectern after a mic drop

To sum up

Record

RecorderHttpClient

Real exchanges, in the standard HAR format

Redact

DefaultRedactor

Secrets, by default, before anything is written

Match

method · URL · body

The right response, in the right order

Replay

MockHttpClient

Without the network, with a simple #[UseRecord]

One attribute, one command, and your tests no longer depend on the network.

Thanks to them

Photo of Nicolas Grekas

Nicolas Grekas

@nicolas-grekas

Photo of Hubert Lenoir

Hubert Lenoir

@Jean-Beru

Photo of Adrien Roches

Adrien Roches

@Neirda24

Photo of Mathieu Santostefano

Mathieu Santostefano

@welcoMattic

Thank you!

Imen Ezzine

@imenezzine

imenezzine.github.io/symfony-con-warsaw-2026