2015-05-19 57 views
3

我做的Symfony2控制器的功能测试,从这个继承我的测试类:用户令牌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('[email protected]', 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()是实例我的学说“用户”实体。

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

在我的应用程序和功能测试中,为了使行为保持一致,我需要做些什么?

+0

执行您的请求时,试试这个方法:'$客户 - >请求(” GET','/ post/12',array(),array(),array( 'PHP_AUTH_USER'=>'username', 'PHP_AUTH_PW'=>'pa $$ word', ));' – smarber

回答

5

查找到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()) 

尤其是$用户PARAM描述

@参数字符串|对象$用户的用户名(如 昵称,电子邮件地址等),或UserInterface实例或 对象

因此,随着应用程序的使用情况,您传递了一个u ser实体在那里作为$用户参数,但是你在测试中传递电子邮件字符串。

所以第一种方式是创建新的用户对象,并用一些测试数据填充它或将其从仓库取像某些用户:

$user = $client->getContainer()->get('doctrine')->getManager()->getRepository('MyAppUserBundle:User')->findOneByEmail('[email protected]'); 
$token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_USER', 'ROLE_ADMIN')); 
+0

Simple回答然后...只是传递一个模拟或真正的用户对象到'UsernamePasswordToken'构造函数而不是一个用户名(正如在Symfony2文档中建议的那样) –

+0

是的! :) –