如何在功能测试期间使用 Symfony2 的会话服务保留数据? [英] How can I persist data with Symfony2's session service during a functional test?

查看:27
本文介绍了如何在功能测试期间使用 Symfony2 的会话服务保留数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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('session')->set('foo', 'bar');. If I output all the session data (using print_r($this->get('session')->all());) either in setUp or in the actual test method, I get back foo => bar. But if I try outputting the session data from the action being tested, I get back an empty array. Does anyone know why this is happening, and how I can prevent it?

我应该注意,如果我从 setUp() 中调用 $_SESSION['foo'] = 'bar' 数据会被持久化,我可以从行动 - 这个问题似乎是 Symfony2 的会话服务的本地问题.

I should note that if I call $_SESSION['foo'] = 'bar' from within setUp() the data is persisted and I can access it from the action - this problem seems local to Symfony2's session service.

推荐答案

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

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();

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

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

这篇关于如何在功能测试期间使用 Symfony2 的会话服务保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆