[英]User token in Symfony2 Functional Tests
I'm doing functional tests of Symfony2 controllers, inheriting my test classes from this: 我正在对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);
}
}
If I use the controller as part of the app: $this->container->get('security.token_storage')->getToken()->getUser()
and $this->getUser()
are instances of my Doctrine "user" entity. 如果我使用控制器作为应用程序的一部分:
$this->container->get('security.token_storage')->getToken()->getUser()
和$this->getUser()
是我的Doctrine的实例“用户“实体。
But when running functional tests: $this->container->get('security.token_storage')->getToken()->getUser()
is a string containing the user name and $this->getUser()
is NULL
. 但是在运行功能测试时:
$this->container->get('security.token_storage')->getToken()->getUser()
是一个包含用户名的字符串, $this->getUser()
为NULL
。
What do I need to do to make behaviour consistent in my app and functional tests? 在我的应用和功能测试中,我需要做些什么才能使行为保持一致?
Look to UsernamePasswordToken source: 查看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())
especially to $user param description 特别是对$ user param的描述
@param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object
@param string | object $ user用户名(如昵称,电子邮件地址等)或UserInterface实例或对象
So with the app usage you are passing an user entity there as $user param, but you are passing the email string at your test. 因此,对于应用程序用法,您将用户实体作为$ user param传递,但是您在测试时传递了电子邮件字符串。
So first way is create new user object and fill it with some test data or get certain user from its repository like: 因此,第一种方法是创建新的用户对象并用一些测试数据填充它或从其存储库中获取某些用户,如:
$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'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.