我正在为使用Symfony2的会话服务获取数据的操作编写功能测试。在我的测试类的setUp
方法中,我调用了$this->get('session')->set('foo', 'bar');
。如果我在print_r($this->get('session')->all());
或实际测试方法中输出所有会话数据(使用setUp
),我会返回foo => bar
。但是如果我尝试从正在测试的动作输出会话数据,我会得到一个空数组。有谁知道为什么会这样,我怎么能阻止它?
我应该注意,如果我在$_SESSION['foo'] = 'bar'
内调用setUp()
数据是持久的,我可以从操作中访问它 - 这个问题似乎是Symfony2会话服务的本地问题。
答案 0 :(得分:7)
首先尝试使用客户端的容器(我假设你正在使用WebTestCase):
$client = static::createClient();
$container = $client->getContainer();
如果仍然无效,请尝试保存会话:
$session = $container->get('session');
$session->set('foo', 'bar');
$session->save();
我没有在功能测试中尝试过,但这就是它在Behat步骤中的工作原理。
答案 1 :(得分:0)
您可以检索“会话”服务。 有了这项服务,您可以:
代码如下:
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