8000 clarifying how to create a public alias for a test · symfony/symfony-docs@f038841 · GitHub
[go: up one dir, main page]

Skip to content

Commit f038841

Browse files
weaverryanjaviereguiluz
authored andcommitted
clarifying how to create a public alias for a test
1 parent 67dd3c1 commit f038841

File tree

1 file changed

+47
-6
lines changed

1 file changed

+47
-6
lines changed

testing.rst

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -562,12 +562,53 @@ command.
562562

563563
.. tip::
564564

565-
Keep in mind that, if a private service is never used as a dependency of another service in
566-
your application, it is then removed from the container. So, if you try to access a private
567-
service in a test through the special test container and that service isn't used elsewhere
568-
you'll get a ``ServiceNotFoundException``. The solution, depending on the context, is to
569-
define the service as explicitly ``public`` or to inject it where you'll need it so Symfony
570-
doesn't remove it.
565+
If a private service is *never* used in your application (outside of your test), it
566+
is *removed* from the container and cannot be accessed as described above. In that
567+
case, you can create a public alias in the ``test`` environment and access it
568+
via that alias:
569+
570+
.. configuration-block::
571+
572+
.. code-block:: yaml
573+
574+
# config/services_test.yaml
575+
services:
576+
# access the service in your test via
577+
# self::$container->get('test.App\Test\SomeTestHelper')
578+
test.App\Test\SomeTestHelper:
579+
# the id of the private service
580+
alias: 'App\Test\SomeTestHelper'
581+
public: true
582+
583+
.. code-block:: xml
584+
585+
<!-- config/services_test.xml -->
586+
<?xml version="1.0" encoding="UTF-8" ?>
587+
<container xmlns="http://symfony.com/schema/dic/services"
588+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
589+
xsi:schemaLocation="http://symfony.com/schema/dic/services
590+
https://symfony.com/schema/dic/services/services-1.0.xsd">
591+
592+
<services>
593+
<!-- ... -->
594+
595+
<service id="test.App\Test\SomeTestHelper" alias="App\Test\SomeTestHelper" public="true"/>
596+
</services>
597+
</container>
598+
599+
.. code-block:: php
600+
601+
// config/services_test.php
602+
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
603+
604+
use App\Service\MessageGenerator;
605+
use App\Updates\SiteUpdateManager;
606+
607+
return function(ContainerConfigurator $configurator) {
608+
// ...
609+
610+
$services->alias('test.App\Test\SomeTestHelper', 'App\Test\SomeTestHelper')->public();
611+
};
571612
572613
.. tip::
573614

0 commit comments

Comments
 (0)
0