Symfony2 功能测试中的用户令牌

User token in Symfony2 Functional Tests

我正在对 Symfony2 控制器进行功能测试,从这里继承我的测试 类:

class InsecureWebTestCase extends WebTestCase {

    protected $client = null;

    public function setUp() {
        $this->client = static::createClient();
        $session = $this->client->getContainer()->get('session');
        $firewall = 'default';
        $token = new UsernamePasswordToken('norbert.scrunge@gmail.com', null, $firewall, array('ROLE_USER', 'ROLE_ADMIN'));
        // $this->client->getContainer()->get('security.context')->setToken($token);
        $session->set("_security_$firewall", serialize($token));
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }

}

如果我将控制器用作应用程序的一部分: $this->container->get('security.token_storage')->getToken()->getUser()$this->getUser() 是我的 Doctrine "user" 实体的实例。

但是当运行功能测试时: $this->container->get('security.token_storage')->getToken()->getUser() 是包含用户名的字符串,$this->getUser()NULL

我需要做什么才能使我的应用和功能测试中的行为保持一致?

查看 UsernamePasswordToken 来源:

class UsernamePasswordToken extends AbstractToken
{

    /**
     * Constructor.
     *
     * @param string|object            $user        The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method.
     * @param string                   $credentials This usually is the password of the user
     * @param string                   $providerKey The provider key
     * @param RoleInterface[]|string[] $roles       An array of roles
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($user, $credentials, $providerKey, array $roles = array())

特别是 $user 参数描述

@param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object

因此,对于应用程序的使用,您将用户实体作为 $user 参数传递到那里,但您将在测试中传递电子邮件字符串。

所以第一种方法是创建新的用户对象并用一些测试数据填充它或从其存储库中获取特定用户,例如:

$user = $client->getContainer()->get('doctrine')->getManager()->getRepository('MyAppUserBundle:User')->findOneByEmail('norbert.scrunge@gmail.com');
$token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_USER', 'ROLE_ADMIN'));