Symfony functional test - controller getUser method returns null

I have a method in my functional test for user login:

/**
 * @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 the user in the controller it returns null.

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

      

Is the login method wrong?

Update

Test Method:

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

      

+3


source to share


1 answer


Try to change:

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

      



to

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

      

+3


source







All Articles