Functional test a controller using session in symfony 6 (after the 'session' service has been deprecated)

164 Views Asked by At

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:

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' );
    }
}
1

There are 1 best solutions below

0
user14965928 On

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 :

$client->loginUser($user);

For other purposes something like this may work ( found when searching the updated way to login an user, not tester ) :

if ($container->has('session.factory')) {
    $session = $container->get('session.factory')->createSession();
} elseif ($container->has('session')) {
    $session = $container->get('session');
}