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测试客户端的主要内容,如果未能解决你的问题,请参考以下文章

在 Php/symfony 中检查用户身份验证

Symfony:事件订阅者。当路由要求用户必须经过身份验证时触发 404 页面(取决于 .env var)

Symfony:如何从数据库中刷新经过身份验证的用户?

从 Symfony3 中经过身份验证的用户 (HWIOAuth) 获取 Angular2 中的 JWT 令牌

Symfony PHPUnit 测试不验证用户

Symfony2 自定义身份验证:用户登录但未通过身份验证