# Laravel 测试专项参考
本文件是
test-generation的 Laravel/PHPUnit 补充参考,不作为独立子技能计数。命中 Laravel、PHPUnit、Pest、Feature Test、Factory、Queue fake、HTTP fake、Sanctum 等信号时按需加载。
test_ 前缀或清晰的 it ... 描述。DB::table()->insert()。Queue::fake(),再执行请求,最后断言。RefreshDatabase:默认选择,保证 migration 与测试数据库一致。DatabaseTransactions:更快,但不能验证 migration;仅在项目明确适配时使用。DatabaseMigrations:每个测试运行/回滚 migration,成本高,只在需要验证迁移行为时使用。assertDatabaseHas()、assertDatabaseMissing();金额 DECIMAL 按字符串断言,避免 float 精度问题。public function test_user_can_update_own_profile(): void
{
Queue::fake();
$user = User::factory()->create();
$response = $this
->actingAs($user)
->patchJson('/api/profile', [
'name' => 'Ada Lovelace',
]);
$response
->assertOk()
->assertJsonPath('success', true)
->assertJsonPath('data.name', 'Ada Lovelace');
$this->assertDatabaseHas('users', [
'id' => $user->id,
'name' => 'Ada Lovelace',
]);
Queue::assertNothingPushed();
}
whenLoaded() 时出现。state():如 active()、suspended()、verified()。afterCreating(),但要避免隐藏过多业务前置条件。| 工具 | 用途 | 断言 |
| - | - | - |
| Queue::fake() | 队列任务 | assertPushed()、assertNothingPushed() |
| Event::fake() | 领域事件 | assertDispatched() |
| Notification::fake() | 通知 | assertSentTo() |
| Mail::fake() | 邮件 | assertSent()、assertQueued() |
| Storage::fake() | 上传/文件写入 | assertExists()、assertMissing() |
| Http::fake() | 外部 API | assertSent()、模拟超时/错误 |
| Bus::fake() | chain/batch | assertChained()、assertBatched() |
服务类 mock 只用于隔离外部边界或昂贵依赖;核心业务规则优先真实执行,避免测试只验证 mock 调用。
with()、withCount()、withExists() 后断言响应字段和查询数量。performance-benchmark。failed() 补偿。then、catch、finally 的状态变更。php artisan test
./vendor/bin/phpunit
./vendor/bin/phpunit --filter test_user_can_update_own_profile
./vendor/bin/phpstan analyse --level=8
交付 Laravel 测试相关任务时,至少提供: