In application tests you rarely make just one request: you submit a form, follow the redirect, click a link, etc. Until now, a lot of what those requests did (the emails they sent, the messages they queued, the services you replaced) was gone by the time you wanted to check it. Symfony 8.2 fixes this and adds new helpers for testing your applications.
Messenger Assertions
FrameworkBundle provides test assertions for Mailer, Notifier, HttpClient and
Console, but there was nothing for Messenger. Testing a flow with an
asynchronous step meant building a Worker by hand in the test, and handler
failures never reached the test because the worker turns them into events.
Symfony 8.2 adds a MessengerAssertionsTrait to KernelTestCase (so it's
also available in WebTestCase). It works with the in-memory transport,
so configure it first in the test environment:
1 2 3 4 5 6
# config/packages/messenger.yaml
when@test:
framework:
messenger:
transports:
async: 'in-memory://'
Then, you can assert on the queued messages and consume them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// tests/Controller/LoanControllerTest.php
namespace App\Tests\Controller;
use App\Message\ScoreLoanApplication;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class LoanControllerTest extends WebTestCase
{
public function testLoanApplicationIsScored(): void
{
$client = static::createClient();
$client->request('POST', '/loans', ['amount' => 25000]);
$client->followRedirect();
// the third argument is optional and counts only the messages of that class
$this->assertQueuedMessageCount(1, 'async', ScoreLoanApplication::class);
// runs a real worker with the bus and listeners of the application
static::consumeQueuedMessages('async');
// ... assert on what the handlers did
}
}
These helpers see the messages queued by all the requests of the test, which is why the example can assert after following the redirect. Retries don't wait for their delay and, when a handler keeps failing, the exception that exhausts the retries is thrown again, so a broken handler fails the test.
Mailer and Notifier Assertions Across Requests
Controllers usually send an email and then redirect. The kernel forgot the
sent emails and notifications before each request of the test client, so
assertEmailCount() found nothing after followRedirect() and you had to
assert before following the redirect.
In Symfony 8.2, the Mailer and Notifier assertions see everything sent during the test, no matter which request sent it:
1 2 3 4 5
$client->request('POST', '/contact', ['message' => 'Hello']);
$client->followRedirect();
$this->assertEmailCount(1);
$this->assertSelectorTextContains('.alert', 'Thanks for your message');
Note
If some test expects no emails after a second request, it now also counts the emails sent by the first one. Update those tests when upgrading.
Webhook Test Helpers
Testing an endpoint of the Webhook component required creating the request
by hand, including its ID, timestamp and signature headers. The new
sendWebhook() method of the test client posts a webhook signed as your
application expects it. Pass the name of the entry in webhook.routing,
the event name and the payload:
1 2 3 4 5 6 7 8 9 10
$client = static::createClient();
$client->sendWebhook('payments', 'payment.succeeded', [
'data' => ['reference' => 'INV-2026-0042'],
]);
$this->assertResponseIsSuccessful();
// sign with another secret to check that the webhook is rejected
$client->sendWebhook('payments', 'payment.succeeded', [], 'whsec_'.base64_encode('not the secret'));
$this->assertResponseStatusCodeSame(406);
This method only works with the routing entries that use the generic request parser of the component. For the parsers of third-party providers, keep creating the request yourself.
For the webhooks that your application sends, the new WebhookAssertionsTrait
provides these assertions about sent webhooks:
1 2 3 4 5 6 7 8
$client->request('POST', '/orders/42/pay');
$this->assertWebhookCount(1);
$this->assertWebhookSent('https://example.com/webhook', 'order.paid', ['order' => 42]);
$this->assertWebhookNotSent('https://example.com/webhook', 'order.refunded');
// a list of SendWebhookMessage objects to make your own assertions
$webhooks = $this->getSentWebhooks();
Sent webhooks still go through the HTTP client, so mock it in your tests as usual.
Container Changes That Survive Kernel Reboots
The test client reboots the kernel before every request except the first one.
This includes the requests made by clickLink(), submitForm() and
followRedirect(). A service replaced with static::getContainer()->set()
is therefore used in one request only. After that, the test gets the original
service back without any error or warning.
Symfony 8.2 adds a configure_container option to createClient(). It's
a closure that the client calls after every kernel boot, so your
replacements are applied to all the requests of the test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
use Psr\Clock\ClockInterface;
use Symfony\Component\Clock\MockClock;
use Symfony\Component\DependencyInjection\ContainerInterface;
$clock = new MockClock('2026-03-01');
$client = static::createClient([
'configure_container' => function (ContainerInterface $container) use ($clock): void {
$container->set(ClockInterface::class, $clock);
},
]);
$client->request('GET', '/invoices/2026-0001');
$this->assertSelectorTextContains('#status', 'Pending');
$clock->modify('+2 months');
// this request reboots the kernel and the closure sets the same clock again
$client->clickLink('Refresh');
$this->assertSelectorTextContains('#status', 'Overdue');
The closure receives the test container, so it can replace private services
too. It can't be combined with insulate(), because closures can't be passed
to another process.
Login in Stateless Firewalls
The loginUser() method of the test client stores a security token in the
session, so stateless firewalls ignore it. Testing an API protected with
access tokens required faking the identity provider or signing tokens by
hand.
In Symfony 8.2, loginUser() also works on stateless firewalls that use
the access_token authenticator, whatever their token handler is:
1 2 3 4 5 6 7 8 9 10 11 12 13
use App\Repository\UserRepository;
use Symfony\Component\Security\Http\Authenticator\AccessTokenAuthenticator;
$client = static::createClient();
$user = static::getContainer()->get(UserRepository::class)->findOneByEmail('jane@example.com');
// the third argument defines the attributes of the security token
$client->loginUser($user, 'api', [
AccessTokenAuthenticator::SCOPE_ATTRIBUTE => ['proposals:write'],
]);
$client->jsonRequest('POST', '/api/proposals', ['title' => 'Testing in Symfony 8.2']);
$this->assertResponseStatusCodeSame(201);
This only happens in the test environment. Also, if a request includes its own
access token, Symfony uses that token instead of the user passed to loginUser().
One Mocked Clock for All Your Code
Symfony provides two ways of mocking time in tests: the MockClock of the
Clock component, for code that uses the clock service, and the
ClockMock of the PHPUnit bridge, for code that calls PHP functions such
as time() and sleep(). They knew nothing about each other, so tests
that involved both kinds of code (e.g. your services and a rate limiter) had
to move two clocks.
In Symfony 8.2, ClockMock follows the global MockClock, so a single
mockTime() call moves both:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// tests/SubscriptionTest.php
namespace App\Tests;
use Symfony\Bridge\PhpUnit\Attribute\TimeSensitive;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Clock\Test\ClockSensitiveTrait;
class SubscriptionTest extends KernelTestCase
{
use ClockSensitiveTrait;
#[TimeSensitive]
public function testTrialExpires(): void
{
$clock = static::mockTime('2030-01-01 00:00:00 UTC');
time(); // 1893456000
$clock->sleep(3600);
time(); // 1893459600
sleep(60);
$clock->now(); // 2030-01-01 01:01:00
}
}
Faster Tests by Default
Hashing passwords is slow on purpose and checking them against the haveibeenpwned.com API requires a network call. That's good in production but not in tests, so the Symfony recipes added some test config to your application to disable both.
In Symfony 8.2, when the framework.test option is enabled, password hashers
use the lowest costs that bcrypt and argon2 accept and the
NotCompromisedPassword constraint accepts all passwords. The new
recipes no longer add that config and you can remove it from your application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# config/packages/security.yaml
- when@test:
- security:
- password_hashers:
- Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
- algorithm: auto
- cost: 4
- time_cost: 3
- memory_cost: 10
# config/packages/validator.yaml
- when@test:
- framework:
- validation:
- not_compromised_password: false
Symfony only changes the options that you don't define. If some test needs the
real behavior, set the cost, time_cost and memory_cost options of
the hasher or enable validation.not_compromised_password explicitly.
Rate Limiters Reset Between Tests
The rate limiters store their state in a cache pool that isn't cleared between tests. So, if a test hit the limit, the next test started already blocked. The usual workaround was to clear that pool before each test.
In Symfony 8.2, rate limiters are reset at the end of each test, so you can remove that code:
1 2 3 4
protected function setUp(): void
{
- static::getContainer()->get('cache.rate_limiter')->clear();
}
The requests of the same test still share the limiter state. If some test
needed the tokens used by a previous test, it must now use them itself.
Limiters with their own cache_pool or storage_service are not reset,
because that pool might store other data.
Service State That Lasts for a Whole Test
Most features of this article need the same thing: state that lives exactly as long as a test. The kernel resets services between requests, which is too soon for the sent emails. Cache pools and files outlive the kernel, which is too late for rate limiters.
Symfony 8.2 adds a kernel.test_state tag to solve both cases, and you can
apply it to your own services. Use the method attribute to call a
method of the service when each test ends:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// src/Storage/LocalFileStorage.php
namespace App\Storage;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
// the stored files outlive the kernel, so remove them when each test ends
#[AutoconfigureTag('kernel.test_state', ['method' => 'clear'])]
class LocalFileStorage
{
public function clear(): void
{
// ...
}
// ...
}
This is also how you reset the custom cache pool of a rate limiter. The other
attribute is keep: true, which tells Symfony to keep a copy of the service
before each reset of the kernel, until the test ends. That's what the Mailer,
Notifier, Messenger and Webhook helpers rely on. The tag does nothing when
framework.test is disabled, so you don't need to restrict it to the test
environment.