Symfony News

New in Symfony 5.1: Simpler login in tests

Wouter De Jong

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('jane.doe@example.com');

        $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!');
    }
}

Be trained by Symfony experts - 2020-03-30 Online Europe - 2020-04-6 Online Europe - 2020-04-6 Online Europe


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook