ServiceDestructionTest.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Drupal\KernelTests\Core\DrupalKernel;
  3. use Drupal\KernelTests\KernelTestBase;
  4. use Symfony\Component\HttpFoundation\Response;
  5. /**
  6. * Tests that services are correctly destructed.
  7. *
  8. * @group DrupalKernel
  9. */
  10. class ServiceDestructionTest extends KernelTestBase {
  11. /**
  12. * Verifies that services are destructed when used.
  13. */
  14. public function testDestructionUsed() {
  15. // Enable the test module to add it to the container.
  16. $this->enableModules(['service_provider_test']);
  17. $request = $this->container->get('request_stack')->getCurrentRequest();
  18. $kernel = $this->container->get('kernel');
  19. $kernel->preHandle($request);
  20. // The service has not been destructed yet.
  21. $this->assertNull(\Drupal::state()->get('service_provider_test.destructed'));
  22. // Call the class and then terminate the kernel
  23. $this->container->get('service_provider_test_class');
  24. $response = new Response();
  25. $kernel->terminate($request, $response);
  26. $this->assertTrue(\Drupal::state()->get('service_provider_test.destructed'));
  27. }
  28. /**
  29. * Verifies that services are not unnecessarily destructed when not used.
  30. */
  31. public function testDestructionUnused() {
  32. // Enable the test module to add it to the container.
  33. $this->enableModules(['service_provider_test']);
  34. $request = $this->container->get('request_stack')->getCurrentRequest();
  35. $kernel = $this->container->get('kernel');
  36. $kernel->preHandle($request);
  37. // The service has not been destructed yet.
  38. $this->assertNull(\Drupal::state()->get('service_provider_test.destructed'));
  39. // Terminate the kernel. The test class has not been called, so it should not
  40. // be destructed.
  41. $response = new Response();
  42. $kernel->terminate($request, $response);
  43. $this->assertNull(\Drupal::state()->get('service_provider_test.destructed'));
  44. }
  45. }