概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:51:05 | 145 次阅读 | 评论: 0 | 来源: 网络整理

Authenticating requests in functional tests might slow down the suite. It could become an issue especially when form_login is used, since it requires additional requests to fill in and submit the form.

One of the solutions is to configure your firewall to use http_basic in the test environment as explained in How to Simulate HTTP Authentication in a Functional Test. Another way would be to create a token yourself and store it in a session. While doing this, you have to make sure that an appropriate cookie is sent with a request. The following example demonstrates this technique:

// src/AppBundle/Tests/Controller/DefaultControllerTest.php
namespace AppbundleTestsController;

use SymfonyBundleFrameworkBundleTestWebTestCase;
use SymfonyComponentBrowserKitCookie;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;

class DefaultControllerTest extends WebTestCase
{
    private $client = null;

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

    public function testSecuredHello()
    {
        $this->logIn();

        $crawler = $this->client->request('GET', '/admin');

        $this->assertTrue($this->client->getResponse()->isSuccessful());
        $this->assertGreaterThan(0, $crawler->filter('html:contains("Admin Dashboard")')->count());
    }

    private function logIn()
    {
        $session = $this->client->getContainer()->get('session');

        $firewall = 'secured_area';
        $token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
        $session->set('_security_'.$firewall, serialize($token));
        $session->save();

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

注解

The technique described in How to Simulate HTTP Authentication in a Functional Test is cleaner and therefore the preferred way.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务