Reputation: 364
In my controllers, I check if a request is fully authenticated against the built-in token_storage - provider by Symfony (version 5.3), as depicted here:
$uid = $this->tokenStorage->getToken()->getUser()->getId();
However, when I try to get the tokenStorage - service in the setUp() - initializer of my WebTest like this:
$this->tokenStorage = static::$kernel->getContainer()->get('security.token_storage');
I get this notice when executing my unit tests:
Since symfony/security-bundle 5.3: Accessing the "security.token_storage" service directly from the container is deprecated, use dependency injection instead.
This seems like a catch 22 - situation, since the suggested dependency injection does not seem to work for unit tests.
Therefore, I get this error when trying to inject the TokenStorageInterface to my WebTest´s - constructor:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Tests\ConnectorTest::__construct(), 0 passed in /var/www/html/vendor/phpunit/phpunit/src/Framework/TestBuilder.php on line 138 and exactly 1 expected in /var/www/html/tests/ConnectorTest.php
Upvotes: 0
Views: 1122
Reputation: 17166
The KernelTestCase and WebTestCase provide a specialized test container you can use to retrieve services you want to test, that are usually not directly available from the container.
Just use the getContainer
-method provided on the TestCase, rather than from the kernel:
static::getContainer()->get(…)
In this container all services are made public and accessible without throwing a deprecation warning.
If this does not suit you, you can also modify your container for the test environment, e.g. by making services public in a separate services_test.yaml
file.
Upvotes: 1