Reputation: 227
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());
}
Upvotes: 3
Views: 2273
Reputation: 227
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()
Upvotes: 1
Reputation: 1959
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());
}
Upvotes: 0