Trait not found inside Laravel 5 unit tests
I'm guessing having the trait in the traits folder, the trait is no longer accounted for in your autoloader.
In order to correct this, you should open up composer.json
, find the sectionfor autoload-dev
and change it to something like the following...
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"tests/Traits/"
]
},
And that should add any traits you have in that folder to the autloader.
Edit
Some additional ideas were brought up in the comments. If you are going to be maintaining proper folder/namespace structure, it would be a good idea to use psr-4 autoloading rather than maintaining the class map.
"autoload-dev": {
"psr-4": {
"MyappTests\\": "tests/"
}
},
Also, rather than put logic in a trait to register a user for use with testing, when you extend TestCase
, it brings in a helper method for logging in as a certain user. You'd use it like so...
$user = User::find($id);
$this->be($user);
I'm developing a JSON REST API, and during tests development I found the need to refactor some of my testing functionalities inside a trait to be used inside test classes.
After renaming a class, PhpStorm wrote in the log something like:
Fatal error: Trait 'controllers\ControllerTestWithUsers2' not found in ...
when I tried to execute my test suite using the renamed trait.
The solution to my problem was to simply run the command composer dump-autoload
and then try again to run my test suite.
I found that this operation has to be done every time a renaming is performed in PhpStorm. It seems that the composer command regenerates some internal files pointing to the old class name, leading to the "Fatal error".