@@ -619,15 +619,58 @@ This allows you to create all types of requests you can think of:
619619 :ref: `framework.test <reference-framework-test >` option is enabled).
620620 This means you can override the service entirely if you need to.
621621
622- .. caution ::
622+ Multiple Requests in One Test
623+ .............................
624+
625+ After you send one request, subsequent ones will make the client reboot
626+ the kernel, recreating the container from scratch.
627+ This ensures that requests are "isolated" using "new" service objects.
628+ However, this can cause some unexpected behaviors. For example, the
629+ security token will be cleared, Doctrine entities will be "detached"…
630+
631+ Calling the client's
632+ :method: `Symfony\\ Bundle\\ FrameworkBundle\\ KernelBrowser::disableReboot `
633+ method is the first step to work around this, as this will reset the kernel
634+ instead of rebooting it. Now, resetting the kernel will call the ``reset() ``
635+ method of every ``kernel.reset `` tagged service, which will **also ** clear
636+ the security token, detach entities and so on.
637+
638+ As such, the next step is to create a
639+ :doc: `compiler pass </service_container/compiler_passes >` to remove the
640+ ``kernel.reset `` tag from these services in your test environment::
641+
642+ // src/Kernel.php
643+ namespace App;
644+
645+ use App\DependencyInjection\Compiler\CustomPass;
646+ use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
647+ use Symfony\Component\DependencyInjection\ContainerBuilder;
648+ use Symfony\Component\HttpKernel\Kernel as BaseKernel;
649+
650+ class Kernel extends BaseKernel
651+ {
652+ use MicroKernelTrait;
653+
654+ // …
623655
624- Before each request, the client reboots the kernel, recreating
625- the container from scratch.
626- This ensures that every requests are "isolated" using "new" service objects.
627- Also, it means that entities loaded by Doctrine repositories will
628- be "detached", so they will need to be refreshed by the manager or
629- queried again from a repository.
630- You can disable this behavior by calling the :method: `disableReboot() <Symfony\\ Bundle\\ FrameworkBundle\\ KernelBrowser::disableReboot> ` method.
656+ protected function build(ContainerBuilder $container): void
657+ {
658+ if ('test' === $this->environment) {
659+ $container->addCompilerPass(new class() implements CompilerPassInterface {
660+ public function process(ContainerBuilder $container): void
661+ {
662+ // prevents the security token to be cleared
663+ $container->getDefinition('security.token_storage')->clearTag('kernel.reset');
664+
665+ // prevents entities to be detached
666+ $container->getDefinition('doctrine')->clearTag('kernel.reset');
667+
668+ // …
669+ }
670+ });
671+ }
672+ }
673+ }
631674
632675Browsing the Site
633676.................
0 commit comments