Symfony 功能测试 - 控制器方法 getUser returns null

Symfony functional test - controller method getUser returns null

我的用户登录功能测试中有方法:

/**
 * @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);
}

当我尝试在控制器中获取用户时,它 returns 为空。

public function editProfile(Request $request)
{
    $user = $this->getUser(); //returns null
    ...
}

是不是登录方式有误?

更新

测试方法:

public function testProfile() {
    ...
    $user = $this->createUser();
    $this->logIn($user);
    $this->client->request('POST', '/profile/edit', $data);
    ...
}

尝试更改:

 $token = new UsernamePasswordToken($user, null, 'main', array('ROLE_USER'));

 $token = new UsernamePasswordToken($user, null, $firewallName, array('ROLE_USER'));