
Laravel 9 移除了默认的 Tests\TestCase 基类文件,升级后若未同步更新测试引导结构,会导致 Class 'Tests\TestCase' not found 致命错误;需手动重建或修复 tests/TestCase.php 并确保其正确继承与配置。
laravel 9 移除了默认的 `tests\testcase` 基类文件,升级后若未同步更新测试引导结构,会导致 `class 'tests\testcase' not found` 致命错误;需手动重建或修复 `tests/testcase.php` 并确保其正确继承与配置。
在 Laravel 9 中,框架对测试基础设施进行了重构:Tests\TestCase 不再由安装脚本自动生成,而是要求开发者显式创建或从新项目中同步该基类。当你从 Laravel 8 升级至 Laravel 9 后,旧版 tests/TestCase.php 可能残留、内容过时,或根本缺失——这正是 Fatal error: Class 'Tests\TestCase' not found 的根本原因。
✅ 正确的 tests/TestCase.php 内容(Laravel 9 标准)
请确保 tests/TestCase.php 文件存在于项目根目录下的 tests/ 文件夹中,并包含以下标准定义:
<?php namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}同时,还需确认 tests/CreatesApplication.php trait 存在且内容正确(Laravel 9 默认提供):
<?php namespace Tests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Testing\CreatesApplication;
trait CreatesApplication
{
public function createApplication(): Application
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
}⚠️ 注意事项:
- 文件路径必须为 tests/TestCase.php(注意大小写和位置);
- 命名空间必须为 Tests(非 Tests\TestCase),否则 use Tests\TestCase; 将无法解析;
- SimpleTest.php 中的 use Tests\TestCase; 引用是正确的,前提是 Tests\TestCase 类真实存在且可自动加载;
- 运行 composer dump-autoload 确保类自动加载映射刷新;
- 若使用 IDE,建议清缓存并重新索引 tests/ 目录。
? 推荐修复流程(一步到位)
- 删除旧的 tests/TestCase.php(如有);
- 从一个全新 Laravel 9 项目中复制标准 tests/TestCase.php 和 tests/CreatesApplication.php;
- 检查 phpunit.xml 中
的 directory 是否指向 tests(默认已正确); - 运行 php artisan test 或 ./vendor/bin/phpunit 验证是否通过。
完成上述操作后,所有基于 Tests\TestCase 的功能测试(如 RefreshDatabase、WithFaker)将恢复正常运行。此问题本质是升级迁移中的“骨架文件缺失”,而非代码逻辑错误,及时补全测试基础结构即可彻底解决。











