php - Symfony2 从 phpunit 测试中的 Twig 模板访问全局变量

标签 php symfony phpunit twig

我有一个带有 {{ app.user }} 的 Twig 模板。问题是,在 phpunit 测试(一个扩展 WebTestCase 的类)中,它被定义为 NULL。使用 token ( http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html ) 模拟身份验证或模拟 HTTP 身份验证 ( http://symfony.com/doc/current/cookbook/testing/http_authentication.html ) 没有帮助。 那么如何从 phpunit 测试中设置一个 twig 全局变量呢?为什么模拟身份验证在这种情况下不起作用?

最佳答案

我有一个类似的问题(正确登录)最终为我解决的是改变我的登录方式(它基于 http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html 但我以不同的方式处理 session ):

public function setUp() {
    parent::setUp();

    $this->em = $this->get('doctrine')->getManager();
    $this->client = static::createClient(array('environment' => 'test'));
}

protected function logIn() {
    $repo = $this->em->getRepository('XXXXXXX');
    $user = $repo->findOneByUsername('YYYYYYY');

    $session = new Session(new MockFileSessionStorage());
    $firewall = 'main';
    $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_ADMIN'));
    $this->client->getContainer()->get('security.context')->setToken($token);
    $session->set('_security_' . $firewall, serialize($token));
    $session->save();

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

    return $user;
}

关于php - Symfony2 从 phpunit 测试中的 Twig 模板访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489149/

相关文章:

Symfony2 : Where to place code running for all routes?

php - 如何在 Symfony 4 控制台命令中获取应用程序根路径

javascript - 如何自定义 FullCalendar Bundle 的数据 [Symfony 4]

php - NetBeans + 多个 php 版本 + 没有 PEAR 的 phpUnit

php - Laravel Mockery - 使用注入(inject)构造函数的依赖项模拟类

php - api的Laravel多路由文件

php - 如何将 Javascript 和 CSS 文件添加到 ZF2 中的布局

php - 在抽象类中测试私有(private)方法会扩展另一个方法

php - 如何通过php代码在mysql服务器上添加用户?

php - 在 CakePHP 中导入 Controller 或模型更好吗?