Share
Embed
Tests in a Symfony Application
Alexandre Salomé
June 16, 2023
Transcript
147 slides
-
Our use case Hello Alice, Thank you for registering! To
confirm your registration, please click on the link below: Happy conferences, The speaker Click here to activate your account From: The App <[email protected]> Subject: Finish your registration -
Application Service Example User Repository Service Mailer Service User Manager
Request Response User -
Different test types 3 test types are defined by Symfony:
1. Unit tests 2. Integration tests 3. Application tests Application tests Integration tests Unit tests -
These tests ensure that individual units of source code (e.g.
a single class) behave as intended. -
Application Service Unit tests User Repository Service Mailer Service User
Manager Request Response User -
Unit tests use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public
function testActivate(): void { $user = new User(); $this→assertFalse($user→isActivated()); $user→activate(); $this→assertTrue($user→isActivated()); } } -
Unit tests use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public
function testActivate(): void { $user = new User(); $this→assertFalse($user→isActivated()); $user→activate(); $this→assertTrue($user→isActivated()); } } -
Unit tests use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public
function testActivate(): void { $user = new User(); $this→assertFalse($user→isActivated()); $user→activate(); $this→assertTrue($user→isActivated()); } } -
Unit tests use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public
function testActivate(): void { $user = new User(); $this→assertFalse($user→isActivated()); $user→activate(); $this→assertTrue($user→isActivated()); } } -
Unit tests use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public
function testActivate(): void public function testActivateTwice(): void public function testActivateWhenLocked(): void } -
Unit tests Pro - Fast to execute - Simple and
fundamental Con - Mock of the dependencies -
These tests test a combination of classes and commonly interact
with Symfony's service container. -
Application Service Integration tests User Repository Service Mailer Service User
Manager Request Response User -
Application Service Integration tests User Repository Service Mailer Service User
Manager Request Response User -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
use App\Entity\User; use App\Manager\UserManager; use App\Test\UserActionsTrait ; use Symfony\Bundle\FrameworkBundle \Test\KernelTestCase
; class RegistrationManagerTest extends KernelTestCase { use UserActionsTrait ; // Helper methods used below public function testRegisterExistingUser (): void { $this->createUser('alice'); $user = new User(); $user->setEmail('[email protected] '); $user->setName('Alice'); $manager = self::getContainer()->get(UserManager::class); $manager->register($user); $this->assertAlreadyRegisteredMailSent (); } } -
Integration tests Pro - They allows testing any service -
The service is in real conditions Con - The coupling of the service is not visible -
Application Service Application tests User Repository Service Mailer Service User
Manager Request Response User -
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class RegisterControllerTest extends WebTestCase { public function testValid():
void { $client = self::createClient(); $crawler = $client→request('GET', '/register'); $form = $crawler→filter('main form')→form([ 'register[name]' => 'Test User', 'register[email]' => '[email protected]', ]); $client→submit($form); $this→assertResponseStatusCodeSame(302); $this→assertResponseRedirects('/register/confirmation'); } } -
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class RegisterControllerTest extends WebTestCase { public function testValid():
void { $client = self::createClient(); $crawler = $client→request('GET', '/register'); $form = $crawler→filter('main form')→form([ 'register[name]' => 'Test User', 'register[email]' => '[email protected]', ]); $client→submit($form); $this→assertResponseStatusCodeSame(302); $this→assertResponseRedirects('/register/confirmation'); } } -
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class RegisterControllerTest extends WebTestCase { public function testValid():
void { $client = self::createClient(); $crawler = $client→request('GET', '/register'); $form = $crawler→filter('main form')→form([ 'register[name]' => 'Test User', 'register[email]' => '[email protected]', ]); $client→submit($form); $this→assertResponseStatusCodeSame(302); $this→assertResponseRedirects('/register/confirmation'); } } -
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class RegisterControllerTest extends WebTestCase { public function testValid():
void { $client = self::createClient(); $crawler = $client→request('GET', '/register'); $form = $crawler→filter('main form')→form([ 'register[name]' => 'Test User', 'register[email]' => '[email protected]', ]); $client→submit($form); $this→assertResponseStatusCodeSame(302); $this→assertResponseRedirects('/register/confirmation'); } } -
PHPUnit 9.5.28 by Sebastian Bergmann and contributors. Testing App\Tests\Manager\User\RegistrationManagerTest F
1 / 1 (100%) Time: 00:00.413, Memory: 32.00 MB There was 1 failure: 1) App\Tests\Manager\User\RegistrationManagerTest::testRegister Failed asserting that Symfony\Component\HttpFoundation\RedirectResponse Object ... ( # ... 'targetUrl' => '/register/actual' ) is redirected and has header "Location" with value "/register/expected". -
PHPUnit 9.5.28 by Sebastian Bergmann and contributors. Testing App\Tests\Manager\User\RegistrationManagerTest F
1 / 1 (100%) Time: 00:00.413, Memory: 32.00 MB There was 1 failure: 1) App\Tests\Manager\User\RegistrationManagerTest::testRegister Failed asserting that Symfony\Component\DomCrawler\Crawler Object ... ( ) matches selector "h1" and the text "register.title" of the node matching selector "body" contains "Register". -
Application tests Pro - They test from outside of the
application - Useful methods in WebTestCase Con - Significant computation cost -
Installing PHPUnit Use the Symfony Test Pack: composer require --dev
symfony/test-pack This will install PHPUnit and the tools we will cover in this presentation. -
Testing email sending public function testRegister(): void { // Fill
and submit the form $crawler = $this→client→request('GET', '/register'); $form = $crawler→filter('form')→form([ 'register[name]' => 'Alice', 'register[email]' => '[email protected]', ]); $this→client→submit($form); $this→assertResponseIsSuccessful(); } -
Testing email sending Hello Alice, Thank you for registering! To
confirm your registration, please click on the link below: Happy conferences, The speaker Click here to activate your account From: The App <[email protected]> Subject: Finish your registration -
// Verify that the registration mail has been sent $this→assertQueuedEmailCount(1);
// Get the email $email = $this→getMailerMessage(); // Assertions on the mail $this→assertEmailHeaderSame( $email, 'Subject', 'Finish your registration' ); $this→assertEmailHtmlBodyContains( $email, 'Click here to activate your account' ); -
// Verify that the registration mail has been sent $this→assertQueuedEmailCount(1);
// Get the email $email = $this→getMailerMessage(); // Assertions on the mail $this→assertEmailHeaderSame( $email, 'Subject', 'Finish your registration' ); $this→assertEmailHtmlBodyContains( $email, 'Click here to activate your account' ); -
// Verify that the registration mail has been sent $this→assertQueuedEmailCount(1);
// Get the email $email = $this→getMailerMessage(); // Assertions on the mail $this→assertEmailHeaderSame( $email, 'Subject', 'Finish your registration' ); $this→assertEmailHtmlBodyContains( $email, 'Click here to activate your account' ); -
// Verify that the registration mail has been sent $this→assertQueuedEmailCount(1);
// Get the email $email = $this→getMailerMessage(); // Assertions on the mail $this→assertEmailHeaderSame( $email, 'Subject', 'Finish your registration' ); $this→assertEmailHtmlBodyContains( $email, 'Click here to activate your account' ); -
// Verify that the registration mail has been sent $this→assertQueuedEmailCount(1);
// Get the email $email = $this→getMailerMessage(); // Assertions on the mail $this→assertEmailHeaderSame( $email, 'Subject', 'Finish your registration' ); $this→assertEmailHtmlBodyContains( $email, 'Click here to activate your account' ); -
Testing email sending Hello Alice, Thank you for registering! To
confirm your registration, please click on the link below: Happy conferences, The speaker Click here to activate your account From: The App <[email protected]> Subject: Finish your registration -
public function testRegister(): void { // ... // Extract the
link $link = (new Crawler($email->getHtmlBody())) ->filter('a:contains("Click here to activate your account")' ) ; $href = $link->attr('href'); // Browse the link $response = $this->client->request('GET', $href); $this->assertResponseIsSuccessful (); } -
public function testRegister(): void { // ... // Extract the
link $link = (new Crawler($email->getHtmlBody())) ->filter('a:contains("Click here to activate your account")' ) ; $href = $link->attr('href'); // Browse the link $response = $this->client->request('GET', $href); $this->assertResponseIsSuccessful (); } -
public function testRegister(): void { // ... // Extract the
link $link = (new Crawler($email->getHtmlBody())) ->filter('a:contains("Click here to activate your account")' ) ; $href = $link->attr('href'); // Browse the link $response = $this->client->request('GET', $href); $this->assertResponseIsSuccessful (); } -
public function testRegister(): void { // ... // Extract the
link $link = (new Crawler($email->getHtmlBody())) ->filter('a:contains("Click here to activate your account")' ) ; $href = $link->attr('href'); // Browse the link $response = $this->client->request('GET', $href); $this->assertResponseIsSuccessful (); } -
public function testRegister(): void { // ... // Extract the
link $link = (new Crawler($email->getHtmlBody())) ->filter('a:contains("Click here to activate your account")' ) ; $href = $link->attr('href'); // Browse the link $response = $this->client->request('GET', $href); $this->assertResponseIsSuccessful (); } -
Messenger tests Suppose that UserManager has the following method: public
function register(User $user): void { $this→repository→save($user); $this→sendRegistrationMail($user); $this→messageBus→dispatch( new RegistrationMessage($user→getId()), ); } -
Messenger tests Suppose that UserManager has the following method: public
function register(User $user): void { $this→repository→save($user); $this→sendRegistrationMail($user); $this→messageBus→dispatch( new RegistrationMessage($user→getId()), ); } -
Messenger tests # app/config/messenger.yaml framework: messenger: transports: async: '%env(MESSENGER_TRANSPORT_DSN)%' when@test:
framework: messenger: transports: async: 'in-memory://' -
Messenger tests We can verify the sending of an event
via the in-memory transport: $transport = self::getContainer()->get('messenger.transport.async' ); $this->assertCount(1, $transport->getSent()); $message = $transport->getSent()[0]->getMessage(); $this->assertInstanceOf (RegistrationMessage ::class, $message); -
Messenger tests We can verify the sending of an event
via the in-memory transport: $transport = self::getContainer()->get('messenger.transport.async' ); $this->assertCount(1, $transport->getSent()); $message = $transport->getSent()[0]->getMessage(); $this->assertInstanceOf (RegistrationMessage ::class, $message); -
Messenger tests We can verify the sending of an event
via the in-memory transport: $transport = self::getContainer()->get('messenger.transport.async' ); $this->assertCount(1, $transport->getSent()); $message = $transport->getSent()[0]->getMessage(); $this->assertInstanceOf (RegistrationMessage ::class, $message); -
Messenger tests We can verify the sending of an event
via the in-memory transport: $transport = self::getContainer()->get('messenger.transport.async' ); $this->assertCount(1, $transport->getSent()); $message = $transport->getSent()[0]->getMessage(); $this->assertInstanceOf (RegistrationMessage ::class, $message); -
Clock mocking Suppose we want to have the following test:
public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
Clock mocking Suppose we want to have the following test:
public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
Clock mocking Suppose we want to have the following test:
public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
Clock mocking Suppose we want to have the following test:
public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
Clock mocking Suppose we want to have the following test:
public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
Clock mocking Thanks to the Symfony test-pack, we only need
one annotation: /** * @group time-sensitive */ public function testIsActivationKeyValid (): void { $user = new User(); $key = $user->getActivationKey (); $this->assertTrue($user->isActivationKeyValid ($key)); sleep(2 * 24 * 60 * 60); // 2 days $this->assertFalse($user->isActivationKeyValid ($key)); } -
This annotation will declare mocks for time(), sleep(), usleep() and
date() in the namespaces of the tested class: - App\Entity\ - App\Tests\Entity\ Calls to the time functions in User & UserTest will use the namespace declarations. Clock mocking -
Clock mocking But… You must use : time(), sleep(), usleep()
et date() As an example, for DateTime et DateTimeImmutable: \DateTimeImmutable ::createFromFormat('U', time()); \DateTimeImmutable ::createFromFormat('U', time()) ->add(new \DateInterval('P2D')) ; -
Hello SetPasswordType A Symfony FormType that takes care of changing
the password: $form = $this->createForm(SetPasswordType ::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $userManager->saveUser($user); } -
Hello SetPasswordType A Symfony FormType that takes care of changing
the password: ->addEventListener (FormEvents::POST_SUBMIT, function (PostSubmitEvent $e) { if (!$e->getForm()->isValid()) { Return; } $user = $e->getData(); $password = $e->getForm()->get('password')->getData(); $hashed = $this->userPasswordHasher ->hashPassword($user, $password); $user->setPassword($hashed); }) -
use Symfony\Component\Form\Test\TypeTestCase; class SetPasswordTypeTest extends TypeTestCase { public function testValid():
void { $user = new User(); $user→setPassword('foo'); $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertEquals('fooHashed', $user→getPassword()); } -
use Symfony\Component\Form\Test\TypeTestCase; class SetPasswordTypeTest extends TypeTestCase { public function testValid():
void { $user = new User(); $user→setPassword('fooHashed'); $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertEquals('barHashed', $user→getPassword()); } -
use Symfony\Component\Form\Test\TypeTestCase; class SetPasswordTypeTest extends TypeTestCase { public function testValid():
void { $user = new User(); $user→setPassword('fooHashed'); $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertEquals('barHashed', $user→getPassword()); } -
use Symfony\Component\Form\Test\TypeTestCase; class SetPasswordTypeTest extends TypeTestCase { public function testValid():
void { $user = new User(); $user→setPassword('fooHashed'); $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertEquals('barHashed', $user→getPassword()); } -
use Symfony\Component\Form\Test\TypeTestCase; class SetPasswordTypeTest extends TypeTestCase { public function testValid():
void { $user = new User(); $user→setPassword('fooHashed'); $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertEquals('barHashed', $user→getPassword()); } -
class SetPasswordTypeTest extends TypeTestCase { private UserPasswordHasherInterface|MockObject $passwordHasher; protected function
getExtensions(): array { $this→passwordHasher = $this→createMock(UserPasswordHasherInterface::class) ; $type = new SetPasswordType($this→passwordHasher); return [ new PreloadedExtension([ $type ], []), ]; } -
class SetPasswordTypeTest extends TypeTestCase { private UserPasswordHasherInterface|MockObject $passwordHasher; protected function
getExtensions(): array { $this→passwordHasher = $this→createMock(UserPasswordHasherInterface::class) ; $type = new SetPasswordType($this→passwordHasher); return [ new PreloadedExtension([ $type ], []), ]; } -
class SetPasswordTypeTest extends TypeTestCase { private UserPasswordHasherInterface|MockObject $passwordHasher; protected function
getExtensions(): array { $this→passwordHasher = $this→createMock(UserPasswordHasherInterface::class) ; $type = new SetPasswordType($this→passwordHasher); return [ new PreloadedExtension([ $type ], []), ]; } -
class SetPasswordTypeTest extends TypeTestCase { private UserPasswordHasherInterface|MockObject $passwordHasher; protected function
getExtensions(): array { $this→passwordHasher = $this→createMock(UserPasswordHasherInterface::class) ; $type = new SetPasswordType($this→passwordHasher); return [ new PreloadedExtension([ $type ], []), ]; } -
We finally declare the expectations for the mock: public function
testValid(): void { $user = new User(); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar') →willReturn('barHashed') ; # ... Form unit tests -
$user = new User(); $user→setPassword('fooHashed'); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar')
→willReturn('barHashed') ; $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertTrue($form→isSynchronized()); $this→assertEquals('barHashed', $user→getPassword()); -
$user = new User(); $user→setPassword('fooHashed'); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar')
→willReturn('barHashed') ; $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertTrue($form→isSynchronized()); $this→assertEquals('barHashed', $user→getPassword()); -
$user = new User(); $user→setPassword('fooHashed'); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar')
→willReturn('barHashed') ; $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertTrue($form→isSynchronized()); $this→assertEquals('barHashed', $user→getPassword()); -
$user = new User(); $user→setPassword('fooHashed'); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar')
→willReturn('barHashed') ; $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertTrue($form→isSynchronized()); $this→assertEquals('barHashed', $user→getPassword()); -
$user = new User(); $user→setPassword('fooHashed'); $this→passwordHasher →expects($this→once()) →method('hashPassword') →with($user, 'bar')
→willReturn('barHashed') ; $form = $this→factory→create(SetPasswordType::class, $user); $form→submit(['password' => [ 'first' => 'bar', 'second' => 'bar', ]]); $this→assertTrue($form→isSynchronized()); $this→assertEquals('barHashed', $user→getPassword()); -
Hello UserActivateCommand Imagine a command bin/console user:activate [email protected]. - [ERROR]
No user found with email "[email protected]". - [INFO] The user with email "[email protected]" is already activated. - [OK] The user with email "[email protected]" has been activated. -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
class ActivateCommandTest extends KernelTestCase { public function testAlreadyActivated(): void {
// Prepare the data $this→user→activate(); $this→manager→saveUser($this→user); $app = new Application(self::bootKernel()); $command = $app→find('user:activate'); $tester = new CommandTester($command); $tester→execute(['email' => '[email protected]']); $tester→assertCommandIsSuccessful(); $this→assertStringContainsString( 'already activated', $tester→getDisplay(), ); } -
Symfony UX Stimulus testing is currently considered as experimental. Symfony
UX Stimulus testing -
import { Application } from '@hotwired/stimulus'; import { clearDOM, mountDOM
} from '@symfony/stimulus-testing'; import HelloController from '../controllers/hello_controller.js'; const startStimulus = () => { const application = Application.start(); application.register('hello', HelloController); }; describe('HelloController', () => { let container; beforeEach(() => { startStimulus(); container = mountDOM('<div data-controller="hello"></div>'); }); afterEach(() => { clearDOM(); }); // Test here }); -
import { Application } from '@hotwired/stimulus'; import { clearDOM, mountDOM
} from '@symfony/stimulus-testing'; import HelloController from '../controllers/hello_controller.js'; const startStimulus = () => { const application = Application.start(); application.register('hello', HelloController); }; describe('HelloController', () => { let container; beforeEach(() => { startStimulus(); container = mountDOM('<div data-controller="hello"></div>'); }); afterEach(() => { clearDOM(); }); // Test here }); -
describe('HelloController', () => { // ... it('connect', async () =>
{ expect(container.textContent).toContain("Hello world"); }); }); -
A CRM in which we synchronize the users through an
HTTP call. class SalesPower { public function __construct( private readonly HttpClientInterface $client, ) { } public function createUser(User $user): void { $this→client→request('PUT', '/users', ...); } } Hello SalesPower -
use Symfony\Component\HttpClient\MockHttpClient; $mock = new MockHttpClient(new MockResponse('OK')); $crm = new
SalesPower($mock); $crm→createUser($alice); Simple test method -
$count = 0; $mock = new MockHttpClient( function (string $method,
string $path) use (&$count) { $this→assertSame(0, $count++); $this→assertSame('PUT', $method); $this→assertSame('/users', $path); return new MockResponse('OK'); } ); $crm = new SalesPower($mock); $crm→createUser($alice); $this→assertSame(1, $count, 'Effective call to the HTTP client'); Advanced test method -
$count = 0; $mock = new MockHttpClient( function (string $method,
string $path) use (&$count) { $this→assertSame(0, $count++); $this→assertSame('PUT', $method); $this→assertSame('/users', $path); return new MockResponse('OK'); } ); $crm = new SalesPower($mock); $crm→createUser($alice); $this→assertSame(1, $count, 'Effective call to the HTTP client'); Advanced test method -
$count = 0; $mock = new MockHttpClient( function (string $method,
string $path) use (&$count) { $this→assertSame(0, $count++); $this→assertSame('PUT', $method); $this→assertSame('/users', $path); return new MockResponse('OK'); } ); $crm = new SalesPower($mock); $crm→createUser($alice); $this→assertSame(1, $count, 'Effective call to the HTTP client'); Advanced test method -
$repository = $this→getMockBuilder(UserRepository::class) →disableOriginalConstructor() →getMock() ; $repository →expects($this→once()) →method('findOneBy') →with(['email'
=> '[email protected]']) →willReturn($alice) ; self::getContainer()→set(UserRepository::class, $repository); $manager = self::getContainer()→get(UserManager::class); $manager→recoverPassword('[email protected]'); $this→assertQueuedEmailCount(1); -
$repository = $this→getMockBuilder(UserRepository::class) →disableOriginalConstructor() →getMock() ; $repository →expects($this→once()) →method('findOneBy') →with(['email'
=> '[email protected]']) →willReturn($alice) ; self::getContainer()→set(UserRepository::class, $repository); $manager = self::getContainer()→get(UserManager::class); $manager→recoverPassword('[email protected]'); $this→assertQueuedEmailCount(1); -
$repository = $this→getMockBuilder(UserRepository::class) →disableOriginalConstructor() →getMock() ; $repository →expects($this→once()) →method('findOneBy') →with(['email'
=> '[email protected]']) →willReturn($alice) ; self::getContainer()→set(UserRepository::class, $repository); $manager = self::getContainer()→get(UserManager::class); $manager→recoverPassword('[email protected]'); $this→assertQueuedEmailCount(1); -
$repository = $this→getMockBuilder(UserRepository::class) →disableOriginalConstructor() →getMock() ; $repository →expects($this→once()) →method('findOneBy') →with(['email'
=> '[email protected]']) →willReturn($alice) ; self::getContainer()→set(UserRepository::class, $repository); $manager = self::getContainer()→get(UserManager::class); $manager→recoverPassword('[email protected]'); $this→assertQueuedEmailCount(1); -
Profiler collectors The test magic is possible because of the
collectors: $this→client→enableProfiler(); $this→client→request('GET', '/'); $collectors = $this→client→getProfile()→getCollectors(); -
- Request - Time - Memory - Validator - Ajax
- Form - Exception - Logger - Events Available collectors - Router - Cache - Security - Twig - Http Client - Database - Messenger - Mailer - Config -
We verify that no request was generated: $collectors = $client→getProfile()→getCollectors();
/** @var HttpClientDataCollector $httpClientCollector */ $httpClientCollector = $collectors['http_client']; $this→assertEquals(0, $httpClientCollector→getRequestCount()); Example with “http_client” -
Fixtures - Useful for development - Risky for automated tests
(data mutation) -
Fixtures - Useful for development - Risky for automated tests
(data mutation) - Prefer data self-sufficient tests -
Self-sufficient test deleting data public function setUp(): void { $this→client
= static::createClient(); $userManager = self::getContainer()→get(UserManager::class); try { $user = $userManager→findOneByEmail('[email protected]'); $userManager→deleteUser($user); } catch (\InvalidArgumentException) { // Ignore } } -
Abstract external services Industrialized example: Symfony Mailer Minimalist example: a
third CRM API: - PUT /user when a user is created - DELETE /user/<ID> when a user is deleted -
namespace App\Crm; interface CrmInterface { /** @throws ApiException */ public
function createUser(User $user): void; /** @throws ApiException */ public function deleteUser(string $id): void; } Create the interface contract -
namespace App\Crm; class SalesPower implements CrmInterface { public function __construct(
private readonly HttpClientInterface $client, ) { } public function createUser(User $user): void { # PUT /user } public function deleteUser(string $id): void { # DELETE /user/<id> } } -
namespace App\Crm; class SalesPower implements CrmInterface { public function __construct(
private readonly HttpClientInterface $client, ) { } public function createUser(User $user): void { # PUT /user } public function deleteUser(string $id): void { # DELETE /user/<id> } } -
namespace App\Crm; class SalesPower implements CrmInterface { public function __construct(
private readonly HttpClientInterface $client, ) { } public function createUser(User $user): void { # PUT /user } public function deleteUser(string $id): void { # DELETE /user/<id> } } -
namespace App\Crm; class SalesPower implements CrmInterface { public function __construct(
private readonly HttpClientInterface $client, ) { } public function createUser(User $user): void { # PUT /user } public function deleteUser(string $id): void { # DELETE /user/<id> } } -
Unit test the class: - This implementation relies on the
Symfony HTTP client - The Symfony HTTP client can be mocked SalesPowerTest -
namespace App\Crm; class InMemoryCrm implements CrmInterface { public array $createdUsers
= []; public array $deletedUserIds = []; public function createUser(User $user): void { $this→createdUsers[] = $user; } public function deleteUser(string $id): void { $this→deletedUserIds[] = $id; } } -
namespace App\Crm; class InMemoryCrm implements CrmInterface { public array $createdUsers
= []; public array $deletedUserIds = []; public function createUser(User $user): void { $this→createdUsers[] = $user; } public function deleteUser(string $id): void { $this→deletedUserIds[] = $id; } } -
class RegisterTest extends WebTestCase { public function testRegister(): void {
/** @var InMemoryCrm $crm */ $crm = self::getContainer()→get(CrmInterface::class); # ... $this→assertCount(1, $crm→createdUsers); } } -
class RegisterTest extends WebTestCase { public function testRegister(): void {
/** @var InMemoryCrm $crm */ $crm = self::getContainer()→get(CrmInterface::class); # ... $this→assertCount(1, $crm→createdUsers); } }