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

时间:2015-04-18 16:49:45

标签: php symfony phpunit

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

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

1 个答案:

答案 0 :(得分:3)

尝试更改:

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

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