Skip to content

[DependencyInjection] Add a section for testing service subscribers #17296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion service_container/service_subscribers_locators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ argument of type ``service_locator``:
# config/services.yaml
services:
App\CommandBus:
arguments:
arguments:
- !service_locator
App\FooCommand: '@app.command_handler.foo'
App\BarCommand: '@app.command_handler.bar'
Expand Down Expand Up @@ -723,4 +723,55 @@ and compose your services with them::
as this will include the trait name, not the class name. Instead, use
``__CLASS__.'::'.__FUNCTION__`` as the service id.

Testing a Service Subscriber
----------------------------

When you need to unit test a service subscriber, you can either create a fake
``ServiceLocator``::

use Symfony\Component\DependencyInjection\ServiceLocator;

$container = new class() extends ServiceLocator {
private $services = [];

public function __construct()
{
parent::__construct([
'foo' => function () {
return $this->services['foo'] = $this->services['foo'] ?? new stdClass();
},
'bar' => function () {
return $this->services['bar'] = $this->services['bar'] ?? $this->createBar();
},
]);
}

private function createBar()
{
$bar = new stdClass();
$bar->foo = $this->get('foo');

return $bar;
}
};

$serviceSubscriber = new MyService($container);
// ...

Or mock it when using ``PHPUnit``::

use Psr\Container\ContainerInterface;

$container = $this->createMock(ContainerInterface::class);
$container->expects(self::any())
->method('get')
->willReturnMap([
['foo', $this->createStub(Foo::class)],
['bar', $this->createStub(Bar::class)],
])
;

$serviceSubscriber = new MyService($container);
// ...

.. _`Command pattern`: https://en.wikipedia.org/wiki/Command_pattern