PHPUnit "Error: Class ... not found" - Fix Autoloading in CI
PHPUnit could not find a class a test references. Composer’s autoloader does not know about it - usually a stale autoload map, a PSR-4 namespace that does not match the directory, or the test autoload (autoload-dev) not installed in CI.
What this error means
A test errors with "Class 'App\\Service\\Foo' not found" (or a test case class not found). The class exists on disk, but Composer’s autoloader cannot resolve it in the CI checkout.
1) Tests\Unit\OrderTest
Error: Class "App\Service\PaymentGateway" not found
/app/src/Order.php:18Common causes
Autoload map not regenerated
New classes were added but composer dump-autoload never ran (or a classmap-optimized build is stale), so the autoloader has no entry for them.
PSR-4 namespace/path mismatch
The namespace in composer.json autoload/autoload-dev does not match the directory structure (case or path), so PSR-4 cannot map the class to a file.
autoload-dev not installed in CI
Running composer install --no-dev omits autoload-dev, so test-only namespaces (e.g. Tests\) are not registered.
How to fix it
Regenerate the autoloader
composer dump-autoload
# or as part of install (keep dev for tests)
composer install --no-interaction --prefer-distAlign PSR-4 mappings
// composer.json
{
"autoload": { "psr-4": { "App\\": "src/" } },
"autoload-dev": { "psr-4": { "Tests\\": "tests/" } }
}How to prevent it
- Keep PSR-4 namespaces aligned with directory paths.
- Run
composer install(with dev) in CI test jobs, not--no-dev. - Commit
composer.lockfor reproducible autoload generation.