Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

symfony

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());
    }
like image 910
Woeler Avatar asked Jul 10 '26 07:07

Woeler


1 Answers

Wanted to let everyone know that I solved my problem by injecting the TokenStorageInterface into my controller, and getting the username via $tokenStorage->getToken()->getUsername()

like image 145
Woeler Avatar answered Jul 11 '26 23:07

Woeler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!