Skip to content

Instantly share code, notes, and snippets.

@lyrixx
Last active February 24, 2026 11:06
Show Gist options
  • Select an option

  • Save lyrixx/0adb8fd414451596557871d2d9af5695 to your computer and use it in GitHub Desktop.

Select an option

Save lyrixx/0adb8fd414451596557871d2d9af5695 to your computer and use it in GitHub Desktop.
Test applications services can boot
<?php
namespace Tests\Integration;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Bundle\FrameworkBundle\Test\TestContainer;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
class ContainerTest extends KernelTestCase
{
public function testContainer()
{
static::bootKernel(['debug' => true]);
/** @var TestContainer $container */
$container = static::getContainer();
/** @var string $projectDir */
$projectDir = $container->getParameter('kernel.project_dir');
/** @var string $containerDumpFile */
$containerDumpFile = $container->getParameter('debug.container.dump');
/** @var ContainerBuilder $dumpedContainer */
$dumpedContainer = unserialize(file_get_contents(substr_replace($containerDumpFile, '.ser', -4)));
$count = 0;
foreach ($dumpedContainer->getDefinitions() as $id => $service) {
if ($this->isSkipped($id, $service, $dumpedContainer, $projectDir)) {
continue;
}
try {
$container->get($id);
} catch (\Throwable $e) {
$this->fail($e->getMessage());
}
++$count;
}
$this->addToAssertionCount($count);
}
private function getFilterList(): array
{
return [
\App\Foo\Bar::class,
];
}
private function isSkipped(string $id, Definition $service, ContainerBuilder $builder, string $projectDir): bool
{
if (\in_array($id, $this->getFilterList(), true)) {
return true;
}
if (str_starts_with($id, '.')) {
return true; // Symfony internal stuff
}
if ($service->isAbstract()) {
return true; // Symfony internal stuff
}
$class = $service->getClass();
if (!$class) {
return true; // kernel, or alias, or abstract
}
$rc = $builder->getReflectionClass($class, false);
if (!$rc) {
return true;
}
$filename = $rc->getFileName();
if (!str_starts_with($filename, "{$projectDir}/src")) {
return true;
}
if ($rc->isAbstract()) {
return true;
}
return false;
}
}
@norkunas
Copy link

Thanks, that works well

@lyrixx
Copy link
Author

lyrixx commented Feb 24, 2026

For the record, I have updated the gist for Symfony 7.4+

Important

for older symfony version, please check older revisions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment