我有一个带{{ 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全局变量呢?为什么模拟认证在这种情况下不起作用?
答案 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;
}