简体   繁体   中英

Symfony functional test - controller method getUser returns null

I have method in in my functional test for user log in:

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

When I try to get user in controller, then it returns null.

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

Is logIn method wrong?

Update

Test method:

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

Try change:

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM