我正在尝试为我的REST API设置一些测试,我需要在请求对象中设置一个会话变量。通常的方法似乎不起作用。
$session = $request->getSession();
$session->set('my_session_variable', 'myvar');
你应该使用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();
如果使用WebTestCase,则可以检索“会话”服务。有了这项服务,您可以:
代码可以是以下内容:
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( .... ...
一个简短的片段,用于在会话中设置一些值
$session = $this->client->getRequest()->getSession();
$session->set('name', 'Sensorario');
这是一个非常简单的例子来获得这个价值
echo $session->get('name');