Skip to content

Commit b051054

Browse files
committed
Merge branch '6.0' into 6.1
* 6.0: [DependencyInjection] Add a section for testing service subscribers
2 parents 8ee0c64 + 4d5b3ad commit b051054

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'
@@ -721,4 +721,54 @@ and compose your services with them::
721721
as this will include the trait name, not the class name. Instead, use
722722
``__CLASS__.'::'.__FUNCTION__`` as the service id.
723723

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

0 commit comments

Comments
 (0)