Symfony2 - Tests with FOSUserBundle

后端 未结 2 1956
生来不讨喜
生来不讨喜 2020-12-28 09:18

i would write a test for Symfony2 with FOSUserBundle.

At the moment i tried some ways and no one works.

I need a function like \"createAuthClient\".

2条回答
  •  礼貌的吻别
    2020-12-28 09:42

    Create an AbstractControllerTest and create an authorized client on setUp() as follow:

    client = $this->createAuthorizedClient();
        }
    
        /**
         * @return Client
         */
        protected 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');
            /** @var $loginManager \FOS\UserBundle\Security\LoginManager */
            $loginManager = $container->get('fos_user.security.login_manager');
            $firewallName = $container->getParameter('fos_user.firewall_name');
    
            $user = $userManager->findUserBy(array('username' => 'REPLACE_WITH_YOUR_TEST_USERNAME'));
            $loginManager->loginUser($firewallName, $user);
    
            // save the login token into the session and put it in a cookie
            $container->get('session')->set('_security_' . $firewallName,
                serialize($container->get('security.context')->getToken()));
            $container->get('session')->save();
            $client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
    
            return $client;
        }
    } 
    

    NOTE: Please, replace the username with your test username.

    Then, extends the AbstractControllerTest and use the global $client to make requests as follow:

    class ControllerTest extends AbstractControllerTest
    {
        public function testIndexAction()
        {
            $crawler = $this->client->request('GET', '/admin/');
    
            $this->assertEquals(
                Response::HTTP_OK,
                $this->client->getResponse()->getStatusCode()
            );
        }
    }
    

    This method tested and works fine

提交回复
热议问题