Symfony2从phpunit测试中的twig模板访问全局变量

时间:2014-05-06 08:02:59

标签: php symfony phpunit twig

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

1 个答案:

答案 0 :(得分:5)

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

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