Symfony 2-在单元测试期间向请求对象添加会话数据



我正在尝试为我的REST API设置一些测试,我需要在请求对象中设置一个会话变量。通常的方法似乎不起作用。

$session = $request->getSession();              
$session->set('my_session_variable', 'myvar');

您应该使用WebTestCase

然后你可以做类似问题的答案中描述的事情:how-can-i-persist-data-with-symfony2session-service-during-a-functional-test

所以类似于:

$client = static::createClient();
$container = $client->getContainer();
$session = $container->get('session');
$session->set('name', 'Sensorario');
$session->save();

如果使用WebTestCase,则可以检索"会话"服务。有了这项服务,您可以:

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

代码可以是以下内容:

use SymfonyComponentBrowserKitCookie;
....
....
public function testARequestWithSession()
{
    $client = static::createClient();
    $session = $client->getContainer()->get('session');
    $session->start(); // optional because the ->set() method do the start
    $session->set('my_session_variable', 'myvar'); // 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 = $this->client->getRequest()->getSession();
$session->set('name', 'Sensorario');

还有一个非常简单的例子,可以得到这个值

echo $session->get('name');