Symfony 4.1功能测试:如何创建授权的客户端

时间:2018-09-07 10:32:46

标签: symfony phpunit fosuserbundle symfony4

我想为我的功能测试创建授权的客户端。

我正在使用Symfony 4.1,PHPUnit 6.5.9和FOSUserBundle进行用户管理。

我尝试了此代码,但无法正常工作:

class BrandTest extends WebTestCase
{
    public function testBrand()
    {
        $client = $this->createAuthorizedClient();

        $client->request('GET', '/account/brand');

        $this->assertTrue($client->getResponse()->isSuccessful());
    }

    public function createAuthorizedClient()
    {
        $client = static::createClient();

        $container = $client->getContainer();

        $session = $container->get('session');

        /** @var $userManager \FOS\UserBundle\Doctrine\UserManager */
        $userManager = $container->get('fos_user.user_manager');

        $firewallName = $container->getParameter('fos_user.firewall_name');

        $user = $userManager->findUserBy(array('email' => 'mymail@gmail.com'));

        $token = new UsernamePasswordToken($user, $user->getPassword(), $firewallName, $user->getRoles());

        $session->set('_security_' . $firewallName, serialize($token));
        $session->save();

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

        return $client;
    }
}

0 个答案:

没有答案