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