php 创建经过身份验证的symfony测试客户端

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 创建经过身份验证的symfony测试客户端相关的知识,希望对你有一定的参考价值。

<?php

namespace Acme\BlogBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {   
        $client = $this->createAuthenticatedClient();
    }   

    private function createAuthenticatedClient()
    {   
        $client = static::createClient();

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

        // Make sure we are redirected to the login page
        $this->assertEquals(302, $client->getResponse()->getStatusCode());
        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/login'));
        $client->followRedirect();

        // submit login form
        $form = $client->getCrawler()->selectButton('Login')->form();
        $client->submit($form, array(
            '_username' => 'admin',
            '_password' => 'admin',
        )); 

        // Login is successful
        $this->assertEquals(302, $client->getResponse()->getStatusCode());
        $this->assertTrue($client->getResponse()->isRedirect('http://localhost/'));
        $client->followRedirect();

        // On the homepage
        $this->assertEquals(200, $client->getResponse()->getStatusCode());

        return $client;
    }   
}
<?php
/**
 * This method goes in your class, does not check for errors and assumes everything is fine
 */
    protected static function createAuthenticatedClient(array $options = array(), array $server = array())
    {   
        $client = static::createClient($options, $server);
        $client->request('GET', '/login');
        $form = $client->getCrawler()->selectButton('Login')->form();
        $client->submit($form, array(
            '_username' => 'admin',
            '_password' => 'admin',
        )); 

        return $client;
    } 

以上是关于php 创建经过身份验证的symfony测试客户端的主要内容,如果未能解决你的问题,请参考以下文章