I have a function to authorize 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); } 

In the tested action there is a piece of code that needs a current user.
$ this-> getUser ()

 $checkResult = $this->get('dwd.service.coupon')->checkCoupon( $coupon, $request->query->all(), $this->getUser()->getPortalId() ); 

And for some reason, in this revenge, the getUser () method returns Null, although I logged in to setUp () in a test.

 /** * Sets up some stuff before test running */ public function setUp() { parent::setUp(); $this->client = static::createClient(); $this->logIn($this->client); } 
  • Did it help you? I have exactly the same situation and it doesn’t help me anyway it returns null? Is it not necessary to create a user mock and token and add it somehow to the container? - Arturas

1 answer 1

The most preferred form of authentication testing is authorization via HTTP. It is described here in more detail: http://symfony.com/doc/current/testing/http_authentication.html

You should enable HTTP authorization in a test environment, like this:

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);