繁体   English   中英

如何在功能测试期间使用Symfony2的会话服务保留数据?

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

我正在为使用Symfony2的会话服务获取数据的操作编写功能测试。 在我的测试类的setUp方法中,我调用$this->get('session')->set('foo', 'bar'); 如果我输出所有会话数据(使用print_r($this->get('session')->all()); )在setUp或实际测试方法中,我得到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步骤中的工作方式。

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

  • 开始会议,
  • 将一些参数设置为session,
  • 保存会话,
  • 将带有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-the-authentication-token

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM