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