I would like to add a "tests" folder in Symfony.
Here is my composer.json :
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle"
},
"classmap": [
"app/AppKernel.php",
"app/AppCache.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
},
"files": [
"vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
]
},
So i add a controller into tests/Controller/TestController.php with a route /Test/Timeout
When i call the route with Postman : No route found for "GET /Test/Timeout"
When i run php bin/console debug:router, the route does not appear.
Did i miss something ?
If i put the TestController into src/AppBundle/Controller the route is find.
Answers
It seems like Symfony is not able to recognize the controllers located in the tests/
directory for routing purposes. This is because Symfony, by default, does not autoload classes from the tests/
directory for routing and other purposes.
To make Symfony recognize controllers located in the tests/
directory, you need to add the namespace mapping for the Tests\
namespace in your composer.json
file. However, you also need to make sure that Symfony's routing system is aware of these controllers.
Here's what you can do:
-
Update
composer.json
: Make sure theautoload-dev
section in yourcomposer.json
file is correctly configured to autoload theTests\
namespace:"autoload-dev": { "psr-4": { "Tests\\": "tests/" } }
This will ensure that classes under the
Tests\
namespace are autoloaded during development. -
Register Routes: Symfony, by default, does not look for controllers in the
tests/
directory for routing. You need to explicitly tell Symfony to look for controllers in thetests/
directory. You can do this by adding a routing configuration file for your tests. Create a file namedtests/_config/routes.yaml
(assuming Symfony 4 or later) and define your routes there:# tests/_config/routes.yaml test_routes: resource: '@Tests/Controller/' type: annotation
This configuration tells Symfony to look for annotations in your controllers under the
Tests\Controller
namespace. -
Annotations in Test Controllers: Make sure your test controllers are annotated with routing information. For example:
// tests/Controller/TestController.php namespace Tests\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; class TestController extends AbstractController { /** * @Route("/Test/Timeout", name="test_timeout") */ public function timeout() { // Controller logic } }
This annotation tells Symfony that the
timeout()
method should be accessible via the/Test/Timeout
URL.
After making these changes, Symfony should be able to recognize and route requests to controllers located in the tests/
directory. Make sure to clear the cache (php bin/console cache:clear
) after making changes to routing configurations.