DependencySerializationTest.php in Drupal 9
File
core/tests/Drupal/Tests/Core/DependencyInjection/DependencySerializationTest.php
View source
<?php
namespace Drupal\Tests\Core\DependencyInjection;
use Drupal\Core\DependencyInjection\Container;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DependencySerializationTest extends UnitTestCase {
public function testSerialization() {
$service = new \stdClass();
$service->_serviceId = 'test_service';
$container = new Container();
$container
->set('test_service', $service);
$container
->set('service_container', $container);
\Drupal::setContainer($container);
$dependencySerialization = new DependencySerializationTestDummy($service);
$dependencySerialization
->setContainer($container);
$string = serialize($dependencySerialization);
$dependencySerialization = unserialize($string);
$this
->assertSame($service, $dependencySerialization->service);
$this
->assertSame($container, $dependencySerialization->container);
$this
->assertEmpty($dependencySerialization
->getServiceIds());
}
public function testSerializationWithMissingService() {
$service = new \stdClass();
$service->_serviceId = 'test_service_not_existing';
$container = new Container();
$container
->set('test_service', $service);
$container
->set('service_container', $container);
\Drupal::setContainer($container);
$dependencySerialization = new DependencySerializationTestDummy($service);
$dependencySerialization
->setContainer($container);
$string = serialize($dependencySerialization);
$dependencySerialization = unserialize($string);
$this
->assertSame($container, $dependencySerialization->container);
}
}
class DependencySerializationTestDummy implements ContainerAwareInterface {
use DependencySerializationTrait;
public $service;
public $container;
public function __construct(\stdClass $service) {
$this->service = $service;
}
public function setContainer(ContainerInterface $container = NULL) {
$this->container = $container;
}
public function getServiceIds() {
return $this->_serviceIds;
}
}