必须运行 php artisan pest:install,否则 tests/pest.php 缺失导致 pest\test 找不到、testcase 未绑定、工厂类不可用,测试无法执行。

直接用 composer require --dev pestphp/pest pestphp/pest-plugin-laravel 就能装上 Pest,但光装包不运行 php artisan pest:install,测试根本跑不起来——因为缺入口、缺 Laravel 上下文绑定、连 tests/Pest.php 都没生成。
为什么 composer require 后还报错 “Class Pest\Test not found”
这是最常卡住的一步:Pest 的核心类 Pest\Test 不是靠 Composer 自动加载进来的,它依赖 php artisan pest:install 生成的 tests/Pest.php 入口文件,并通过 uses(Tests\TestCase::class) 注册测试基类。如果只装包不执行安装命令:
-
tests/Pest.php不存在 → Pest 找不到启动逻辑 -
Tests\TestCase不会被自动挂载 →$this->get()、$this->postJson()全部失效 - 即使手写
it()函数,也会因上下文缺失而报app() is null或Call to undefined method get()
php artisan pest:install 做了什么,哪些不能跳过
这个命令不是“可选优化”,而是强制前置步骤。它实际完成四件事:
- 创建
tests/Pest.php,并写入uses(Tests\TestCase::class)->in('Feature', 'Unit') - 把原
tests/Feature/ExampleTest.php转成 Pest 写法(删旧建新) - 替换
phpunit.xml中的bootstrap指向tests/Pest.php - 注册
pest-plugin-laravel,让RefreshDatabase、WithoutMiddleware等 Trait 可直接uses()引入
跳过任意一项,比如手动改 phpunit.xml 却漏掉 tests/Pest.php,或删了 tests/Pest.php 又没重装,测试就会静默失败或报路径错误。
工作流任务拆解与模型编排技能。使用场景:(1) 收到复杂工作任务需要拆解为可执行步骤,(2) 需要为不同步骤选择最合适的模型,(3) 需要跟踪工作流进度和模型使用情况,(4) 长时间任务卡住需要问题诊断和解决方案。
运行测试时该用 ./vendor/bin/pest 还是 php artisan test
两者都行,但行为有关键差异:
-
./vendor/bin/pest是 Pest 原生命令,支持--watch、--parallel、--filter等高级选项,适合开发阶段快速反馈 -
php artisan test是 Laravel 封装命令,会自动加载phpunit.xml配置(包括DB_CONNECTION=sqlite和DB_DATABASE=:memory:),CI 环境更稳定 - 别混用:如果在
phpunit.xml里关了processIsolation,但用./vendor/bin/pest --parallel,可能因共享内存导致数据库事务冲突
测试里调用 User::factory()->create() 报 “Class not found” 怎么办
这不是 Composer 问题,是工厂类未被自动发现或命名空间错位:
- Laravel 9+ 移除了全局
factory()函数,必须用模型静态调用:User::factory()->create() - 确认
database/factories/UserFactory.php的命名空间是Database\Factories,且protected $model = User::class指向正确类(含完整命名空间,如App\Models\User) - 如果模型在
App\Models下,工厂里不能写use app\models\user(小写)——PHP 对命名空间大小写敏感,尤其在 CI 的 Linux 环境下必报错
真正容易被忽略的是:Pest 测试文件本身不参与 Composer classmap 自动加载,它靠 Laravel 的测试启动流程动态注册工厂。一旦 uses(Tests\TestCase::class) 缺失或 TestCase 没继承 Illuminate\Foundation\Testing\TestCase,工厂就彻底不可见。










