In controllers in Symfony 5 I used to inject the Session and use it.
class MyNiceController
{
public function __invoke( Session $session )
{
$this->useTheSession( $session );
}
}
In the tests, I used to get it via the container and hack it like this:
class MyNiceControllerTest
{
public function testWhatever()
{
$client = static::createClient();
$session = $client->getContainer()->get( 'session' );
$session->set( 'intialize-some-key', 'with-some-data' );
$crawler = $client->request( 'GET', '/some-path' );
}
}
Nevertheless, in Symfony 6 we should not use the session service directly as it's been deprecated:
- Deprecation note here: https://symfony.com/blog/new-in-symfony-5-3-session-service-deprecation
- Usage of
Requestinstead ofRequestStackhere: https://symfony.com/doc/current/session.html
In fact using $client->getContainer()->get( 'session' ); fails.
Okey. The controller should be used like this:
class MyNiceController
{
public function __invoke( Request $request )
{
$session = $request->getSession();
$this->useTheSession( $session );
}
}
Question
I'm lost on how should I prepare the mock with the session data.
class MyNiceControllerTest
{
public function testWhatever()
{
$client = static::createClient();
$session = ??????????????????????????????????;
$session->set( 'intialize-some-key', 'with-some-data' );
$crawler = $client->request( 'GET', '/some-path' );
}
}
I don't exactly know what your a trying to achieve with sessions but, for user login purposes and since symfony 5.1, you can use :
For other purposes something like this may work ( found when searching the updated way to login an user, not tester ) :