How can I persist data with Symfony2's session service during a functional test?

后端 未结 2 1904
挽巷
挽巷 2021-01-19 04:39

I\'m writing a functional test for an action that uses Symfony2\'s session service to fetch data. In my test class\'s setUp method, I call $this->get(\

相关标签:
2条回答
  • 2021-01-19 04:58

    Firstly try using your client's container (I'm assuming you're using WebTestCase):

    $client = static::createClient();
    $container = $client->getContainer();
    

    If it still doesn't work try saving the session:

    $session = $container->get('session');
    $session->set('foo', 'bar');
    $session->save();
    

    I didn't try it in functional tests but that's how it works in Behat steps.

    0 讨论(0)
  • 2021-01-19 05:00

    You can retrieve the "session" service. With this service, you can :

    • start the session,
    • set some parameters into session,
    • save the session,
    • pass the Cookie with sessionId to the request

    The code can be the following :

    use Symfony\Component\BrowserKit\Cookie;
    ....
    ....
    public function testARequestWithSession()
    {
        $client = static::createClient();
        $session = $client->getContainer()->get('session');
        $session->start(); // optional because the ->set() method do the start
        $session->set('foo', 'bar'); // the session is started  here if you do not use the ->start() method
        $session->save(); // important if you want to persist the params
        $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));  // important if you want that the request retrieve the session
    
        $client->request( .... ...
    

    The Cookie with $session->getId() has to be created after the start of the session

    See Documentation http://symfony.com/doc/current/testing/http_authentication.html#creating-the-authentication-token

    0 讨论(0)
提交回复
热议问题