Andrei Pall

Linux Software Engineering

Testing Symfony Login Pages

In Symfony 8, the recommended way to test pages that require authentication is to use functional tests with WebTestCase and the loginUser() method.

Symfony allows you to simulate an authenticated user without having to submit the login form for every test. You can also test the actual login process, user roles, access restrictions and logout functionality.

1. Install the testing dependencies

If you haven’t already installed the Symfony testing package, run:

composer require --dev symfony/test-pack

This provides the tools required for functional testing, including PHPUnit, BrowserKit and DomCrawler.

Your project structure could look like this:

project/
├── config/
├── src/
│   ├── Controller/
│   ├── Entity/
│   │   └── User.php
│   └── Repository/
│       └── UserRepository.php
├── tests/
│   └── Controller/
│       ├── DashboardControllerTest.php
│       ├── AdminControllerTest.php
│       └── SecurityControllerTest.php
├── .env
├── .env.test
└── phpunit.dist.xml

2. Configure a separate test database

You should avoid running functional tests against your production or development database.

Configure your test database in .env.test.local:

DATABASE_URL="mysql://testuser:password@127.0.0.1:3306/myapp_test?serverVersion=8.4&charset=utf8mb4"

Create the test database:

php bin/console doctrine:database:create --env=test

Execute the migrations:

php bin/console doctrine:migrations:migrate --env=test --no-interaction

Check config/packages/doctrine.yaml for the dbname_suffix setting. Symfony projects commonly append _test automatically in the test environment. If this is configured, use the base database name in your URL to avoid creating myapp_test_test.

You will need test users in this database, preferably created using Doctrine fixtures.

3. Create test users using Doctrine fixtures

Install DoctrineFixturesBundle:

composer require --dev orm-fixtures

Create a fixture class:

src/DataFixtures/UserFixtures.php

<?php

namespace App\DataFixtures;

use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserFixtures extends Fixture
{
    public function __construct(
        private UserPasswordHasherInterface $passwordHasher
    ) {
    }

    public function load(ObjectManager $manager): void
    {
        // Create a regular user
        $user = new User();
        $user->setEmail('user@example.com');
        $user->setRoles(['ROLE_USER']);

        $user->setPassword(
            $this->passwordHasher->hashPassword($user, 'TestPassword123')
        );

        $manager->persist($user);

        // Create an administrator
        $admin = new User();
        $admin->setEmail('admin@example.com');
        $admin->setRoles(['ROLE_ADMIN']);

        $admin->setPassword(
            $this->passwordHasher->hashPassword($admin, 'TestPassword123')
        );

        $manager->persist($admin);

        $manager->flush();
    }
}

Load the fixtures into the test database:

php bin/console doctrine:fixtures:load --env=test --no-interaction

You now have two accounts available for testing:

Email Password Role
user\@example.com TestPassword123 ROLE_USER
admin\@example.com TestPassword123 ROLE_ADMIN

Important: Loading fixtures purges existing database records by default. Make sure you are using the test database.

4. Configure page access restrictions

For the following examples, assume you have these access restrictions in config/packages/security.yaml:

security:
    role_hierarchy:
        ROLE_ADMIN: ROLE_USER

    # Existing providers and firewalls

    access_control:
        - { path: ^/login$, roles: PUBLIC_ACCESS }
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/dashboard, roles: ROLE_USER }
        - { path: ^/profile, roles: ROLE_USER }

The expected behaviour is:

Page Anonymous user Regular user Administrator
/login 200 200* 200*
/dashboard 302 200 200
/profile 302 200 200
/admin 302 403 200

*The login controller may redirect already authenticated users instead.

5. Test a page as an authenticated user

Create the following file:

tests/Controller/DashboardControllerTest.php

<?php

namespace App\Tests\Controller;

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

class DashboardControllerTest extends WebTestCase
{
    public function testAuthenticatedUserCanAccessDashboard(): void
    {
        $client = static::createClient();

        $userRepository = static::getContainer()
            ->get(UserRepository::class);

        $user = $userRepository->findOneBy([
            'email' => 'user@example.com'
        ]);

        self::assertNotNull($user);

        // Simulate login
        $client->loginUser($user);

        // Access the protected page
        $client->request('GET', '/dashboard');

        // Verify the response
        self::assertResponseIsSuccessful();

        // Verify the page content
        self::assertSelectorTextContains('h1', 'Dashboard');
    }
}

How it works

Create test HTTP client

static::createClient()

Retrieve test user from the database

UserRepository

Create authenticated session

$client->loginUser($user)

Request the protected page

GET /dashboard

Symfony checks user permissions

HTTP 200 OK

Verify response and page content

The loginUser() method establishes an authenticated test session without checking the user’s password or submitting the login form. Authorization restrictions remain active.

image

symfony.com+1

This makes functional tests faster.

6. Test access without authentication

You should also verify that unauthenticated users cannot access protected pages.

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

    $client->request('GET', '/dashboard');

    self::assertResponseRedirects('/login');
}

You can also follow the redirect and verify the login page:

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

    $client->request('GET', '/dashboard');

    self::assertResponseRedirects('/login');

    $client->followRedirect();

    self::assertResponseIsSuccessful();
    self::assertSelectorExists('form');
}

This verifies that the page is actually protected.

7. Test pages that require specific roles

For example, suppose an administration page requires ROLE_ADMIN.

tests/Controller/AdminControllerTest.php

<?php

namespace App\Tests\Controller;

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

class AdminControllerTest extends WebTestCase
{
    public function testAdminCanAccessAdminPage(): void
    {
        $client = static::createClient();

        $userRepository = static::getContainer()
            ->get(UserRepository::class);

        $admin = $userRepository->findOneBy([
            'email' => 'admin@example.com'
        ]);

        self::assertNotNull($admin);

        $client->loginUser($admin);

        $client->request('GET', '/admin');

        self::assertResponseIsSuccessful();
    }

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

        $userRepository = static::getContainer()
            ->get(UserRepository::class);

        $user = $userRepository->findOneBy([
            'email' => 'user@example.com'
        ]);

        self::assertNotNull($user);

        $client->loginUser($user);

        $client->request('GET', '/admin');

        self::assertResponseStatusCodeSame(403);
    }

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

        $client->request('GET', '/admin');

        self::assertResponseRedirects('/login');
    }
}

This tests all three possible scenarios:

Administrator

ROLE_ADMIN

200 OK

Regular user

ROLE_USER

403 Forbidden

Anonymous user

Not authenticated

302 Redirect

8. Test the actual login form

Although loginUser() is useful for protected pages, you should separately test whether the authentication mechanism works.

Assuming your login form contains fields named _username and _password and a button labelled Sign in:

tests/Controller/SecurityControllerTest.php

<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SecurityControllerTest extends WebTestCase
{
    public function testSuccessfulLogin(): void
    {
        $client = static::createClient();

        $client->request('GET', '/login');

        $client->submitForm('Sign in', [
            '_username' => 'user@example.com',
            '_password' => 'TestPassword123',
        ]);

        self::assertResponseRedirects('/dashboard');

        $client->followRedirect();

        self::assertResponseIsSuccessful();
        self::assertSelectorTextContains('h1', 'Dashboard');
    }

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

        $client->request('GET', '/login');

        $client->submitForm('Sign in', [
            '_username' => 'user@example.com',
            '_password' => 'WrongPassword',
        ]);

        self::assertResponseRedirects('/login');

        $client->followRedirect();

        self::assertSelectorTextContains(
            '.alert-danger',
            'Invalid credentials'
        );

        // Verify that the user is still unauthenticated
        $client->request('GET', '/dashboard');

        self::assertResponseRedirects('/login');
    }
}

Using submitForm() also submits hidden form fields, including the CSRF token if present.

Adapt the field names, button label, redirect destination and error message to your application’s login implementation.

9. Test logout functionality

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

    $userRepository = static::getContainer()
        ->get(\App\Repository\UserRepository::class);

    $user = $userRepository->findOneBy([
        'email' => 'user@example.com'
    ]);

    self::assertNotNull($user);

    $client->loginUser($user);

    $client->request('GET', '/dashboard');

    self::assertResponseIsSuccessful();

    // Click the logout link rendered by the application
    $client->clickLink('Logout');

    self::assertResponseRedirects();

    // Verify that the protected page is no longer accessible
    $client->request('GET', '/dashboard');

    self::assertResponseRedirects('/login');
}

Using the actual logout link also allows you to test logout URLs containing CSRF tokens.

10. Create a reusable authenticated test client

If your application has many protected pages, retrieving the user in every test becomes repetitive.

Create a base test class:

tests/AuthenticatedWebTestCase.php

<?php

namespace App\Tests;

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

abstract class AuthenticatedWebTestCase extends WebTestCase
{
    protected function createAuthenticatedClient(
        string $email = 'user@example.com'
    ): KernelBrowser {
        $client = static::createClient();

        $userRepository = static::getContainer()
            ->get(UserRepository::class);

        $user = $userRepository->findOneBy([
            'email' => $email
        ]);

        self::assertNotNull($user, 'Test user not found: '.$email);

        $client->loginUser($user);

        return $client;
    }

    protected function createAdminClient(): KernelBrowser
    {
        return $this->createAuthenticatedClient(
            'admin@example.com'
        );
    }
}

Now you can use this class across your entire application.

Dashboard test

<?php

namespace App\Tests\Controller;

use App\Tests\AuthenticatedWebTestCase;

class DashboardControllerTest extends AuthenticatedWebTestCase
{
    public function testDashboard(): void
    {
        $client = $this->createAuthenticatedClient();

        $client->request('GET', '/dashboard');

        self::assertResponseIsSuccessful();
    }
}

Administration test

<?php

namespace App\Tests\Controller;

use App\Tests\AuthenticatedWebTestCase;

class AdminControllerTest extends AuthenticatedWebTestCase
{
    public function testAdminPage(): void
    {
        $client = $this->createAdminClient();

        $client->request('GET', '/admin');

        self::assertResponseIsSuccessful();
    }
}

This is the approach I recommend for larger Symfony applications. It reduces duplicated authentication code and makes tests easier to maintain.

11. Test multiple protected pages using a data provider

If you want to test many pages, you don’t need to create a separate test method for each URL.

PHPUnit supports the #[DataProvider] attribute.

tests/Controller/ProtectedPagesTest.php

<?php

namespace App\Tests\Controller;

use App\Tests\AuthenticatedWebTestCase;
use PHPUnit\Framework\Attributes\DataProvider;

class ProtectedPagesTest extends AuthenticatedWebTestCase
{
    public static function protectedPages(): iterable
    {
        yield 'Dashboard' => ['/dashboard'];
        yield 'Profile' => ['/profile'];
        yield 'Settings' => ['/settings'];
        yield 'Reports' => ['/reports'];
        yield 'Archives' => ['/archives'];
    }

    #[DataProvider('protectedPages')]
    public function testAuthenticatedAccess(string $url): void
    {
        $client = $this->createAuthenticatedClient();

        $client->request('GET', $url);

        self::assertResponseIsSuccessful();
    }

    #[DataProvider('protectedPages')]
    public function testAnonymousAccess(string $url): void
    {
        $client = static::createClient();

        $client->request('GET', $url);

        self::assertResponseRedirects('/login');
    }
}

PHPUnit executes each test method once for every URL provided.

In this example, you have five URLs and two test methods, resulting in 10 independent tests.

12. Test authenticated form submissions

You can also test operations such as adding, editing or deleting records while authenticated.

public function testCreateArchive(): void
{
    $client = $this->createAdminClient();

    $client->request('GET', '/archives/new');

    self::assertResponseIsSuccessful();

    $client->submitForm('Save', [
        'archive[title]' => 'Test archive',
        'archive[url]' => 'https://example.com',
    ]);

    self::assertResponseRedirects('/archives');

    $client->followRedirect();

    self::assertResponseIsSuccessful();

    self::assertSelectorTextContains(
        'body',
        'Test archive'
    );
}

You should also verify that the record was actually persisted in the database:

$archiveRepository = static::getContainer()
    ->get(\App\Repository\ArchiveRepository::class);

$archive = $archiveRepository->findOneBy([
    'title' => 'Test archive'
]);

self::assertNotNull($archive);

self::assertSame(
    'https://example.com',
    $archive->getUrl()
);

For tests that modify the database, reset its state between tests or use transaction-based isolation to prevent tests from interfering with each other.

13. Useful Symfony test assertions

Assertion Description
assertResponseIsSuccessful() Verify HTTP 2xx
assertResponseStatusCodeSame(200) Verify exact HTTP status
assertResponseRedirects('/login') Verify redirect destination
assertSelectorExists('form') Verify that an HTML element exists
assertSelectorNotExists('.error') Verify that an element doesn’t exist
assertSelectorTextContains('h1', 'Dashboard') Verify element content
assertSelectorCount(5, 'table tbody tr') Verify number of elements
assertPageTitleContains('Dashboard') Verify page title
assertRouteSame('app_dashboard') Verify matched route
assertEmailCount(1) Verify number of sent emails

For example, you can verify that the administration menu is not displayed to regular users:

self::assertSelectorNotExists('#admin-menu');

However, hiding a menu item is not a security restriction. You should also directly request the corresponding URL and verify the response.

14. Using a different security firewall

By default, loginUser() uses the main firewall context.

If you have another firewall, such as:

security:
    firewalls:
        backend:
            pattern: ^/admin
            lazy: true
            provider: app_user_provider

            form_login:
                login_path: app_login
                check_path: app_login

You can specify it explicitly:

$client->loginUser($admin, 'backend');

If the firewall has a custom shared security context, use that context name instead.

For stateless JWT or API authentication, you generally need to provide the appropriate authentication header:

$client->request('GET', '/api/archives', [], [], [
    'HTTP_AUTHORIZATION' => 'Bearer '.$token,
]);

self::assertResponseIsSuccessful();

Symfony 8.2 additionally introduces support for loginUser() with stateless firewalls using the Symfony access_token authenticator.

image

symfony.com

15. Testing pages that use JavaScript

WebTestCase does not execute JavaScript.

If your Symfony pages use Stimulus, Turbo, AJAX, dynamic forms or other client-side functionality, you can use Symfony Panther for real browser testing.

image

symfony.com

Install Panther:

composer require --dev symfony/panther

Example:

<?php

namespace App\Tests\EndToEnd;

use Symfony\Component\Panther\PantherTestCase;

class LoginTest extends PantherTestCase
{
    public function testLogin(): void
    {
        $client = static::createPantherClient();

        $client->request('GET', '/login');

        $client->submitForm('Sign in', [
            '_username' => 'user@example.com',
            '_password' => 'TestPassword123',
        ]);

        $client->waitFor('#dashboard');

        self::assertSelectorTextContains('h1', 'Dashboard');
    }
}

Panther requires a supported browser and browser driver. Ensure the application launched by Panther also uses your test database.

WebTestCase vs Panther

Feature WebTestCase Panther
Executes PHP Yes Yes
Executes JavaScript No Yes
Uses a real browser No Yes
Supports loginUser() for session authentication Yes No
Form submissions Yes Yes
AJAX requests triggered by JavaScript No Yes
Screenshots No Yes
Testing speed Fast Slower
Test type Functional End-to-end

16. Run the tests

Run all tests:

php bin/phpunit

Run all controller tests:

php bin/phpunit tests/Controller/

Run a specific test file:

php bin/phpunit tests/Controller/DashboardControllerTest.php

Run a specific test method:

php bin/phpunit --filter testAuthenticatedUserCanAccessDashboard

Run tests with detailed output:

php bin/phpunit --testdox

For a Symfony 8 application with authenticated pages, I recommend the following structure:

tests/
├── AuthenticatedWebTestCase.php
├── Controller/
│   ├── SecurityControllerTest.php
│   ├── ProtectedPagesTest.php
│   ├── DashboardControllerTest.php
│   ├── AdminControllerTest.php
│   └── ArchiveControllerTest.php
├── EndToEnd/
│   └── LoginTest.php
├── Repository/
│   └── UserRepositoryTest.php
└── Service/
    └── ArchiveServiceTest.php

Prioritize the following test cases:

Test case Expected result Testing method
Valid login Authentication succeeds submitForm()
Invalid password Authentication fails submitForm()
Anonymous access Redirect to login WebTestCase
Authenticated access HTTP 200 loginUser()
Insufficient permissions HTTP 403 loginUser()
Administrator access HTTP 200 loginUser()
Access to another user’s restricted records HTTP 403 or 404 loginUser()
Logout Session authentication removed WebTestCase
Invalid CSRF token Operation rejected WebTestCase
Authenticated CRUD operations Database correctly modified WebTestCase
JavaScript interactions Correct browser behaviour Panther

Use WebTestCase + loginUser() for most tests, Doctrine fixtures for test accounts, data providers for testing multiple pages, and Panther only where real browser functionality is necessary.

The examples assume Doctrine ORM, email-based authentication, a session-based firewall and conventional login routes. I haven’t executed them against your specific application, so entity properties, routes and form selectors may need adjustment.

Official documentation

Newer >>