Rebooting Symfony 3.3 container services in controller tests

I have a series of tests for controllers that rely on third-party APIs that need to be mocked in a test environment. We redefine the functional test client finder and exhaust the dependencies we need for testing. The key point here is that the variability changes with each test.

In Symfony 3.2, this worked well, but in Symfony 3.3 I have a few warnings about obsolescence due to the way services are now being introduced:

An example of a test example of a controller:

class MyControllerTest extends WebTestCase { private static $kernelModifier = null; public function setKernelModifier(\Closure $kernelModifier) { self::$kernelModifier = $kernelModifier; $this->ensureKernelShutdown(); } protected static function createClient(array $options = [], array $server = []) { static::bootKernel($options); if ($kernelModifier = self::$kernelModifier) { $kernelModifier->__invoke(); self::$kernelModifier = null; }; $client = static::$kernel->getContainer()->get('test.client'); $client->setServerParameters($server); return $client; } protected function getPropertyClient() { $mockService = (new PropertyMock())->getPropertyMock(); $this->setKernelModifier(function () use ($mockService) { static::$kernel->getContainer()->set('app.property_service', $mockService); }); return static::createClient(); } protected function getPropertyFailureClient() { $mockService = (new PropertyMock())->getPropertyFailureMock(); $this->setKernelModifier(function () use ($mockService) { static::$kernel->getContainer()->set('app.property_service', $mockService); }); return static::createClient(); } } 

Actual Test:

 public function testInvalidPropertyRequest() { $client = $this->getPropertyClient(); $client->request( 'POST', '/webhook/property', [], [], [], '' ); $this->assertEquals(400, $client->getResponse()->getStatusCode()); } 

Deprecation Error:

Setting the predefined service "app.property_service" is deprecated from Symfony 3.3 and will no longer be supported in Symfony 4.0: 3x

I went through the 3.3 release documentation, BC breaks and deprecations, and cannot figure out how I am going to replace container services with mocks after they have been configured.

Any help is appreciated.

+7
php dependency-injection symfony phpunit
source share
1 answer

I also run into this problem, and there is no hint in the Contain class on how to deal with this deprecated one.

// for everyone interested, there the current problem is open on github - but no real solution, except for one, has much more boot code for your unit tests or for testing controllers in isolation. I would recommend that all controllers be defined as services with fixed / defined dependencies and not have direct use of DIC.

+2
source share

All Articles