New in Symfony 5.1: Simpler login in tests

Contributed by
Wouter De Jong
in #35997.

In functional tests, testing protected pages requires logging in as a user. Reproducing the actual login process (e.g. typing a username and password in a login form and submitting it) makes tests slow. Symfony recommends this trick as a faster alternative, but it may not fit your needs.

That's why in Symfony 5.1 we've added a new loginUser() method to simulate the full user login inside a test. Pass the UserInterface object of the user you want to login and that's all:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// tests/Controller/ProfileControllerTest.php
namespace App\Tests\Controller;

use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ProfileControllerTest extends WebTestCase
{
    // ...

    public function testVisitingWhileLoggedIn()
    {
        $client = static::createClient();

        // get or create the user somehow (e.g. creating some users only
        // for tests while loading the test fixtures)
        $userRepository = static::$container->get(UserRepository::class);
        $testUser = $userRepository->findOneByEmail('[email protected]');

        $client->loginUser($testUser);

        // user is now logged in, so you can test protected resources
        $client->request('GET', '/profile');
        $this->assertResponseIsSuccessful();
        $this->assertSelectorTextContains('h1', 'Hello Username!');
    }
}

Comments

wow ! nice feature !!
Great! Looking forward to testing this :)
Finally ! :)
Simple like feature, Great!!!!!!
Thanks 😊
Login with SymfonyConnect to post a comment