Skip to content

Instantly share code, notes, and snippets.

@GromNaN
Created December 15, 2021 20:43
Show Gist options
  • Save GromNaN/c09a4761e8907f0e1fc5ceeab3b88045 to your computer and use it in GitHub Desktop.
Save GromNaN/c09a4761e8907f0e1fc5ceeab3b88045 to your computer and use it in GitHub Desktop.
Symfony Integration test for route configuration: controller does neither exist as service nor as class
<?php
namespace Tests\Integration;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Integration test for Symfony. Validate that all routes are configured with a valid controller.
*
* @author Jérôme Tamarelle (@GromNaN)
*/
class RouterTest extends KernelTestCase
{
public function testRouteControllerExist()
{
self::bootKernel();
/** @var RouterInterface $router */
$router = self::$kernel->getContainer()->get('router');
$controllerResolver = $this->getControllerResolver(self::$kernel->getContainer()->get('http_kernel'));
$errors = [];
foreach ($router->getRouteCollection()->all() as $name => $route) {
$request = new Request();
$request->attributes->set('_controller', $controller = $route->getDefault('_controller'));
try {
$controllerResolver->getController($request);
} catch (\InvalidArgumentException $exception) {
$errors[$name] = $controller;
}
}
$this->assertSame([], $errors, 'Some controller does neither exist as service nor as class.');
}
private function getControllerResolver(HttpKernelInterface $httpKernel): ControllerResolverInterface
{
$reflection = new \ReflectionClass($httpKernel);
$property = $reflection->getProperty('resolver');
$property->setAccessible(true);
return $property->getValue($httpKernel);
}
}
@TomasVotruba
Copy link

TomasVotruba commented Jun 3, 2022

Thanks for sharing this! I'm just adding it 😉

I see you're using reflection to get controller resolver.
I checked our tests and there we get ControllerResolver directly like this:

$this->controllerResolver = self::$container->get('debug.controller_resolver');

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