'Symfony Deprecation on SessionTokenStorage when generating a csrf token in phpunit functionnal tests

I'm on symfony 5.4

I didn't understand what symfony really need in order to correct this deprecation:

Since symfony/security-csrf 5.3: Using the "Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage" without a session has no effect and is deprecated. It will throw a "Symfony\Component\HttpFoundation\Exception\SessionNotFoundException" in Symfony 6.0 1x in MeansCablesControllerTest::TestDatagridAdd from App\Tests\Controller

My function in tests/Controller/MeansBenchesControllerTest.php (WebTestCase) :

function datagridAddUpdate($controllerName, $dataArray)
    {
        $client = static::createClient();
        
        $usersRepository = static::getContainer()->get(UsersRepository::class);
        $testUserAdmin = $usersRepository->find(1);
        
        $client->loginUser($testUserAdmin);

        $csrfToken = $client->getContainer()->get('security.csrf.token_manager')->getToken($controllerName.'Token_item');

        $dataArray['_token'] = $csrfToken;

        $crawler = $client->request('POST', '/datagridAddUpdate/'.$controllerName,$dataArray, [], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);

        $this->assertResponseIsSuccessful('Status code 2xx pour datagridAdd : '.$controllerName);

    }


Solution 1:[1]

Running this before building the form will make sure there is a session available for it:

$request = new Request();
$request->setSession(new Session(new MockArraySessionStorage()));

self::getContainer()->get(RequestStack::class)->push($request);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bart