Symfony3: Controller sees no user authorised from PHPUnit
-
I have a function to copy a test user.
/** * Login function for user. * * @param Client $client */ private function logIn(Client $client) { $session = $client->getContainer()->get('session');
/** @var User $user */ $user = $client->getContainer()->get('doctrine')->getRepository('DWDAdminBundle:User')->find(1); $firewall = 'main'; $token = new UsernamePasswordToken($user, null, $firewall, ['ROLE_ADMIN']); $client->getContainer()->get('security.token_storage')->setToken($token); $session->set('_security_'.$firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $client->getCookieJar()->set($cookie);
}
There's a piece of the code in the tested exche that needs a current user.
$this-stategetUser()$checkResult = $this->get('dwd.service.coupon')->checkCoupon(
$coupon,
$request->query->all(),
$this->getUser()->getPortalId()
);
And for some reason, the way getUser(s) returns Null, even though I did copy in setUp() in the test.
/**
-
Sets up some stuff before test running
*/
public function setUp()
{
parent::setUp();$this->client = static::createClient();
$this->logIn($this->client);
}
-
-
The preferred type of authentication test is the authorisation via HTTP. It is described here in greater detail: http://symfony.com/doc/current/testing/http_authentication.html
You should include HTTP authorisation in the test environment, like:
config_test.yml:
security: firewalls: main: http_basic: ~
In the test file:
$credentials = [ 'PHP_AUTH_USER' => 'testuser', 'PHP_AUTH_PW' => '111', ]; $client = static::createClient([], $credentials);