简体   繁体   English

Symfony控制器功能测试中的$ this-> getUser()返回null

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

I'm trying to test a controller that uses $this->getUser()->getUsername(). 我正在尝试测试使用$ this-> getUser()-> getUsername()的控制器。 It complains that getUsername() is called on null. 它抱怨说getUsername()是在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. 我尝试实例化一个用户对象,并将其传递给UsernamePasswordToken,但也没有运气。

using Symfony 4. 使用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 尝试从logInAsAdmin函数返回$ client

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()获取用户名来解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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