我在用户登录的功能测试中有方法:
/**
* @param User $user
*/
private function logIn(User $user)
{
$firewallName = 'site';
$session = $this->client->getContainer()->get('session');
$securityContext = $this->client->getContainer()->get('security.context');
$token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));
$securityContext->setToken($token);
$session->set('_security_'.$firewallName, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
当我尝试让用户进入控制器时,它会返回null。
public function editProfile(Request $request)
{
$user = $this->getUser(); //returns null
...
}
logIn方法错了吗?
更新
测试方法:
public function testProfile() {
...
$user = $this->createUser();
$this->logIn($user);
$this->client->request('POST', '/profile/edit', $data);
...
}
答案 0 :(得分:3)
尝试更改:
$token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));
到
$token = new UsernamePasswordToken($user, null, $firewallName, array('ROLE_USER'));