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

问题描述 投票:0回答:3

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

$session = $request->getSession();              
$session->set('my_session_variable', 'myvar');
symfony
3个回答
1
投票

你应该使用WebTestCase

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

像这样的东西:

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

1
投票

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

  • 开始会议,
  • 将一些参数设置为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('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( .... ...

-1
投票

一个简短的片段,用于在会话中设置一些值

$session = $this->client->getRequest()->getSession();
$session->set('name', 'Sensorario');

这是一个非常简单的例子来获得这个价值

echo $session->get('name');
© www.soinside.com 2019 - 2024. All rights reserved.