如何使用Symfony2';s会话服务


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

我正在编写一个操作的功能测试,该操作使用Symfony2的会话服务来获取数据。在测试类的setUp方法中,我调用$this->get('session')->set('foo', 'bar');。如果我在setUp或实际测试方法中输出所有会话数据(使用print_r($this->get('session')->all());),则返回foo => bar。但是,如果我尝试从正在测试的操作输出会话数据,我会得到一个空数组。有人知道为什么会发生这种事吗?我该如何预防?

我应该注意,如果我从setUp()中调用$_SESSION['foo'] = 'bar',数据将被持久化,并且我可以从操作中访问它——这个问题似乎是Symfony2的会话服务的本地问题。

首先尝试使用客户端的容器(我假设您使用的是WebTestCase):

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

如果仍然不起作用,请尝试保存会话:

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

我没有在功能测试中尝试过,但这就是它在Behat步骤中的工作方式。

您可以检索"会话"服务。有了这项服务,您可以:

  • 启动会话
  • 在会话中设置一些参数
  • 保存会话
  • 将带有sessionId的Cookie传递给请求

代码可以是以下内容:

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( .... ...

会话开始后,必须创建带有$session->getId()的Cookie

请参阅文档http://symfony.com/doc/current/testing/http_authentication.html#creating-身份验证令牌