2015-05-19 106 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

是的! :) –