Reputation: 153
Accoring to documentation I'm trying to mock session in my PHPUnit test:
public function testAction()
{
$session = new Session(new MockArraySessionStorage());
$session->set('abc', 'xyz');
$client = static::createClient();
$client->getContainer()->set('session', $session);
$client->request('GET', '/');
}
And in my controller I trying to get session value:
public function mainAction()
{
$session = $this->get('session');
var_dump($session->get('abc'), $session->all());die; //returns null and []
}
Why this stuff doesn't work?
Upvotes: 3
Views: 2997
Reputation: 96
I believe it's because the session is resolved with the cookie, and you don't set the cookie who link the session to the client.
You should add:
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
There is a full example to log in a user:
$session = $this->_container->get('session');
$user = $this->_em->getRepository('UserBundle:User')
->findOneByEmail($email);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$session->set('_security_<security_context>', serialize($token));
$session->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
Hope it help
Upvotes: 3