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!');
}
}
|
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
New in Symfony 5.1: Simpler login in tests symfony.com/blog/new-in-symfony-5-1-simpler-login-in-tests
Tweet thisComments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Guillaume Ponty said on Mar 23, 2020 at 11:22 #1