Created
December 15, 2021 20:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: