Assetic Bundles 缓存 Composer 配置 控制台 控制器 调试 部署 Doctrine 电子邮件 事件分发器 表达式 表单 前端 日志 分析器 请求 路由 安全 序列化 服务容器 会话 PSR 7 Symfony 版本 模板 测试 升级 验证 Web 服务器 Web 服务 工作流

发布于 2015-12-06 07:30:03 | 195 次阅读 | 评论: 0 | 来源: 网络整理

功能测试中的认证请求可能会延缓程序组。尤其当使用 form_login 的时候,它可能成为问题,因为它需要额外的填写和提交表单的需求。

解决办法之一是在测试环境中像如何在功能测试中模拟 HTTP 认证中解释的用法一样来设置防火墙使用 http_basic。另一个方法是您自己创建一个 token 并将它储存在一个会话中。当您这样做的时候,您必须确认一个适当的 cookie 随着一个请求发送。下面的例子演示了这一技术:

// src/AppBundle/Tests/Controller/DefaultControllerTest.php
namespace Appbundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

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);
    }
}

这一技术在如何在功能测试中模拟 HTTP 认证中解释得更为整齐,是首选方式。

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

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