简体   繁体   中英

Symfony2 access to Global Variables from a twig template in phpunit test

I have a twig template with {{ app.user }} . The problem is, that in a phpunit test (a class, which extends WebTestCase ) it is defined as NULL. Simulating Authentication with a Token ( http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html ) or simulating HTTP Authentification ( http://symfony.com/doc/current/cookbook/testing/http_authentication.html ) does not help. So how can I set a twig global variable from a phpunit test? And why simulating authentification is not working in this case?

I had a similar problem (logging in properly) what solved it finally for me was to change the way I log in(it's based on http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html but I handle the session differently):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM