@@ -567,6 +567,62 @@ command.
567
567
If the information you need to check is available from the profiler, use
568
568
it instead.
569
569
570
+ Logging in Users (Authentication)
571
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
572
+
573
+ .. versionadded :: 5.1
574
+
575
+ The ``loginUser() `` method was introduced in Symfony 5.1.
576
+
577
+ When you want to add functional tests for protected pages, you have to
578
+ first "login" as a user. Reproducing the actual steps - such as
579
+ submitting a login form - make a test very slow. For this reason, Symfony
580
+ provides a ``loginUser() `` method to simulate logging in in your functional
581
+ tests.
582
+
583
+ Instead of login in with real users, it's recommended to create a user only for
584
+ tests. You can do that with Doctrine :ref: `data fixtures <user-data-fixture >`,
585
+ to load the testing users only in the test database.
586
+
587
+ After loading users in your database, use your user repository to fetch
588
+ this user and use
589
+ :method: `$client->loginUser() <Symfony\\ Bundle\\ FrameworkBundle\\ KernelBrowser::loginUser> `
590
+ to simulate a login request::
591
+
592
+ // tests/Controller/ProfileControllerTest.php
593
+ namespace App\Tests\Controller;
594
+
595
+ use App\Repository\UserRepository;
596
+ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
597
+
598
+ class ProfileControllerTest extends WebTestCase
599
+ {
600
+ // ...
601
+
602
+ public function testVisitingWhileLoggedIn()
603
+ {
604
+ $client = static::createClient();
605
+ $userRepository = static::$container->get(UserRepository::class);
606
+
607
+ // retrieve the test user
608
+ $testUser = $userRepository->findOneByEmail('john.doe@example.com');
609
+
610
+ // simulate $testUser being logged in
611
+ $client->loginUser($testUser);
612
+
613
+ // test e.g. the profile page
614
+ $client->request('GET', '/profile');
615
+ $this->assertResponseIsSuccessful();
616
+ $this->assertSelectorTextContains('h1', 'Hello John!');
617
+ }
618
+ }
619
+
620
+ You can pass any
621
+ :class: `Symfony\\ Component\\ Security\\ Core\\ User\\ UserInterface ` instance to
622
+ ``loginUser() ``. This method creates a special
623
+ :class: `Symfony\\ Bundle\\ FrameworkBundle\\ Test\\ TestBrowserToken ` object and
624
+ stores in the session of the test client.
625
+
570
626
Accessing the Profiler Data
571
627
~~~~~~~~~~~~~~~~~~~~~~~~~~~
572
628
0 commit comments