Skip to content

Commit 6f201de

Browse files
committed
Merge branch '4.4' into 5.4
* 4.4: [DependencyInjection] Add a section for testing service subscribers
2 parents 65ebe2d + 23aed78 commit 6f201de

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

service_container/service_subscribers_locators.rst

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ argument of type ``service_locator``:
256256
# config/services.yaml
257257
services:
258258
App\CommandBus:
259-
arguments:
259+
arguments:
260260
- !service_locator
261261
App\FooCommand: '@app.command_handler.foo'
262262
App\BarCommand: '@app.command_handler.bar'
@@ -731,4 +731,54 @@ and compose your services with them::
731731
return type were *subscribed*. This still works in 5.4 but is deprecated (only
732732
when using PHP 8) and will be removed in 6.0.
733733

734+
Testing a Service Subscriber
735+
----------------------------
736+
737+
To unit test a service subscriber, you can create a fake ``ServiceLocator``::
738+
739+
use Symfony\Component\DependencyInjection\ServiceLocator;
740+
741+
$container = new class() extends ServiceLocator {
742+
private $services = [];
743+
744+
public function __construct()
745+
{
746+
parent::__construct([
747+
'foo' => function () {
748+
return $this->services['foo'] = $this->services['foo'] ?? new stdClass();
749+
},
750+
'bar' => function () {
751+
return $this->services['bar'] = $this->services['bar'] ?? $this->createBar();
752+
},
753+
]);
754+
}
755+
756+
private function createBar()
757+
{
758+
$bar = new stdClass();
759+
$bar->foo = $this->get('foo');
760+
761+
return $bar;
762+
}
763+
};
764+
765+
$serviceSubscriber = new MyService($container);
766+
// ...
767+
768+
Another alternative is to mock it using ``PHPUnit``::
769+
770+
use Psr\Container\ContainerInterface;
771+
772+
$container = $this->createMock(ContainerInterface::class);
773+
$container->expects(self::any())
774+
->method('get')
775+
->willReturnMap([
776+
['foo', $this->createStub(Foo::class)],
777+
['bar', $this->createStub(Bar::class)],
778+
])
779+
;
780+
781+
$serviceSubscriber = new MyService($container);
782+
// ...
783+
734784
.. _`Command pattern`: https://en.wikipedia.org/wiki/Command_pattern

0 commit comments

Comments
 (0)