@@ -837,4 +837,54 @@ Here's an example::
837837
838838 The above example requires using ``3.2 `` version or newer of ``symfony/service-contracts ``.
839839
840+ Testing a Service Subscriber
841+ ----------------------------
842+
843+ To unit test a service subscriber, you can create a fake ``ServiceLocator ``::
844+
845+ use Symfony\Component\DependencyInjection\ServiceLocator;
846+
847+ $container = new class() extends ServiceLocator {
848+ private $services = [];
849+
850+ public function __construct()
851+ {
852+ parent::__construct([
853+ 'foo' => function () {
854+ return $this->services['foo'] = $this->services['foo'] ?? new stdClass();
855+ },
856+ 'bar' => function () {
857+ return $this->services['bar'] = $this->services['bar'] ?? $this->createBar();
858+ },
859+ ]);
860+ }
861+
862+ private function createBar()
863+ {
864+ $bar = new stdClass();
865+ $bar->foo = $this->get('foo');
866+
867+ return $bar;
868+ }
869+ };
870+
871+ $serviceSubscriber = new MyService($container);
872+ // ...
873+
874+ Another alternative is to mock it using ``PHPUnit ``::
875+
876+ use Psr\Container\ContainerInterface;
877+
878+ $container = $this->createMock(ContainerInterface::class);
879+ $container->expects(self::any())
880+ ->method('get')
881+ ->willReturnMap([
882+ ['foo', $this->createStub(Foo::class)],
883+ ['bar', $this->createStub(Bar::class)],
884+ ])
885+ ;
886+
887+ $serviceSubscriber = new MyService($container);
888+ // ...
889+
840890.. _`Command pattern` : https://en.wikipedia.org/wiki/Command_pattern
0 commit comments