Symfony 4 Phpunit functional test

  functional-testing, phpunit, symfony

My functional test return always code 302 with a redirect to my login page.

I looked the official Symfony documentation. I tried the two methods.

Symfony documentation

Here is my test code

<?php

namespace AppTestsController;

use AppRepositoryUserRepository;
use SymfonyBundleFrameworkBundleTestWebTestCase;
use SymfonyComponentBrowserKitCookie;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityGuardTokenPostAuthenticationGuardToken;


class SecurityControllerTest extends WebTestCase {

    private $client = null;
    private $entityManager;

    public function setUp(){

        $this->client = static::createClient();

        $kernel = self::bootKernel();

        $this->entityManager = $kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }
    
    public function testShowLogin(){

        $this->logIn();

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

        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());

    }

    public function testShowProducts(){

        $this->setUp();

        $this->client->request('GET', '/account/list-product');

        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());

    }

    private function logIn(){

        $session = self::$container->get('session');

        $user = $this->entityManager->getRepository(User::class)->getUser(1);

        $firewallName = 'firewallName';

        $firewallContext = 'firewallContext';

        $token = new PostAuthenticationGuardToken($user, $firewallName, $user->getRoles());
        $session->set('_security_'.$firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);

    }
}

Here is my response

<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='http://localhost/login'" />

        <title>Redirecting to http://localhost/login</title>
    </head>
    <body>
        Redirecting to <a href="http://localhost/login">http://localhost/login</a>.
    </body>
</html>

Here is my test result

Failed asserting that 302 matches expected 200.

I have the good user, with the good roles. I also tried a another firewall configuration without success.

My first test testShowLogin() return code 200.

thank you !

Source: Symfony Questions

LEAVE A COMMENT