简体   繁体   中英

$this->getUser() in Symfony controller functional test returns null

I'm trying to test a controller that uses $this->getUser()->getUsername(). It complains that getUsername() is called on null.

Here is my client login code from the test class

protected function logInAsAdmin(Client $client): void
    {
        $session = $client->getContainer()->get('session');

        $firewallName = 'main';
        $firewallContext = 'main';

        $roles = [
            'ROLE_USER',
            'ROLE_ADMIN',
        ];

        $token = new UsernamePasswordToken('admin', null, $firewallName, $roles);
        $session->set('_security_' . $firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $client->getCookieJar()->set($cookie);
    }

And here is what the controller does:

public function home(EmployerRepository $employerRepository, AuthorizationCheckerInterface $authorizationChecker): Response
    {
        if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
            $jobs = [];

            foreach ($employerRepository->findBy(['owner' => $this->getUser()->getUsername()]) as $employer) {
                $jobs = array_merge($jobs, $employer->getJobs()->toArray());
            }

            return $this->render('home.html.twig', ['jobs' => $jobs]);
        }

        return $this->redirectToRoute('login');
    }

Can anyone tell me why this does not work? I tried instantiating a user object and passing that into the UsernamePasswordToken, but no luck with that either.

using Symfony 4.

The test:

/**
     * @test
     */
    public function indexPageIsRenderedWhenLoggedIn(): void
    {
        $client = static::createClient();
        $this->logInAsAdmin($client);
        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertRegExp('/Your jobs/', $client->getResponse()->getContent());
    }

Try to return $client from logInAsAdmin function

protected function logInAsAdmin(Client $client): Client
{
    $session = $client->getContainer()->get('session');

    $firewallName = 'main';
    $firewallContext = 'main';

    $roles = [
        'ROLE_USER',
        'ROLE_ADMIN',
    ];

    $token = new UsernamePasswordToken('admin', null, $firewallName, $roles);
    $session->set('_security_' . $firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $client->getCookieJar()->set($cookie);
    return $client;
}

and use in test:

 /**
 * @test
 */
public function indexPageIsRenderedWhenLoggedIn(): void
{
    $client = static::createClient();
    $client = $this->logInAsAdmin($client);
    $client->request('GET', '/');
    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    $this->assertRegExp('/Your jobs/', $client->getResponse()->getContent());
}

想让所有人都知道我通过将TokenStorageInterface注入控制器中并通过$tokenStorage->getToken()->getUsername()获取用户名来解决了我的问题。

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