Custom Token in Symfony2 Functional Tests
I am running functional tests on Symfony2 controllers by inheriting my test classes:
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 a controller as part of my application:
$this->container->get('security.token_storage')->getToken()->getUser()
and $this->getUser()
are instances of my Doctrine "user principal".
But when running functional tests:
$this->container->get('security.token_storage')->getToken()->getUser()
is the string containing the username and $this->getUser()
- NULL
.
What do I need to do to align the behavior in my application and functional tests?
source to share
Look at the source for 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 for describing the $ user parameter
@param string | object $ user Username (like alias, email, etc.) or UserInterface instance or object
So when using the app, you pass the custom object there as $ user param, but you pass the email string in your test.
So the first way is to create a new custom object and fill it with some test data, or get a specific user from your repository, for example:
$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'));
source to share