如何在 Symfony 4 的功能测试中对用户进行身份验证

How do I authenticate user in functional test on Symfony 4

我正在测试受 IsGranted('ROLE_ADMIN') 注释保护的页面。如何发出模拟具有 'ROLE_ADMIN' 角色的经过身份验证的用户的请求?

我用了this

<?php

namespace App\Tests\Controller;


use Symfony\Component\BrowserKit\Cookie;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

/**
 * Test Page controller
 */
class PageControllerTest extends WebTestCase
{

    private $client = null;

    public function setUp()
    {
        $this->client = static::createClient();
    }

    public function testHomePage()
    {
        $client = static::createClient();
        $client->request('GET', '/');
        $this->assertTrue($client->getResponse()->isRedirect('/login'));
    }

    public function testHomePageSuccess()
    {
        $this->logIn();
        $this->client->request('GET', '/');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
    }

    private function logIn()
    {
        $session = $this->client->getContainer()->get('session');
        $firewallName = 'main';
        $firewallContext = 'main';
        $token = new UsernamePasswordToken('admin', null, $firewallName, ['ROLE_ADMIN']);
       $session->set('_security_'.$firewallContext, serialize($token));
       $session->save();

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