laravel-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel Testing

Laravel 测试

Agent Workflow (MANDATORY)

Agent工作流(必填)

Before ANY implementation, use
TeamCreate
to spawn 3 agents:
  1. fuse-ai-pilot:explore-codebase - Analyze existing test patterns
  2. fuse-ai-pilot:research-expert - Verify Pest/PHPUnit docs via Context7
  3. mcp__context7__query-docs - Check assertion and mocking patterns
After implementation, run fuse-ai-pilot:sniper for validation.

在开始任何实现工作前,使用
TeamCreate
生成3个Agent:
  1. fuse-ai-pilot:explore-codebase - 分析现有测试模式
  2. fuse-ai-pilot:research-expert - 通过Context7验证Pest/PHPUnit文档
  3. mcp__context7__query-docs - 检查断言和模拟模式
实现完成后,运行fuse-ai-pilot:sniper进行验证。

Overview

概述

TypePurposeLocation
FeatureHTTP, full stack
tests/Feature/
UnitIsolated classes
tests/Unit/
ArchCode architecture
tests/Arch.php

类型用途位置
功能测试HTTP、全栈测试
tests/Feature/
单元测试独立类测试
tests/Unit/
架构测试代码架构检查
tests/Arch.php

Decision Guide: Test Type

测试类型决策指南

What to test?
├── HTTP endpoint → Feature test
├── Service/Policy logic → Unit test
├── Code structure → Arch test
├── External API → Mock with Http::fake()
├── Mail/Queue/Event → Use Fakes
└── Database state → assertDatabaseHas()

要测试什么?
├── HTTP端点 → 功能测试
├── 服务/策略逻辑 → 单元测试
├── 代码结构 → 架构测试
├── 外部API → 使用Http::fake()模拟
├── 邮件/队列/事件 → 使用假对象(Fakes)
└── 数据库状态 → assertDatabaseHas()

Decision Guide: Test Strategy

测试策略决策指南

Coverage strategy?
├── Feature tests (70%) → Critical flows
├── Unit tests (25%) → Business logic
├── E2E tests (5%) → User journeys
└── Arch tests → Structural rules

覆盖率策略?
├── 功能测试(70%) → 核心流程
├── 单元测试(25%) → 业务逻辑
├── 端到端测试(5%) → 用户旅程
└── 架构测试 → 结构规则

Critical Rules

核心规则

  1. Use RefreshDatabase for database isolation
  2. Use factories for test data (never raw inserts)
  3. Mock external services - Never call real APIs
  4. Test edge cases - Empty, null, boundaries
  5. Run parallel -
    pest --parallel
    for speed

  1. 使用RefreshDatabase 实现数据库隔离
  2. 使用工厂(factories) 生成测试数据(绝不要直接插入原始数据)
  3. 模拟外部服务 - 绝不调用真实API
  4. 测试边缘情况 - 空值、Null、边界值
  5. 并行运行 - 使用
    pest --parallel
    提升速度

Reference Guide

参考指南

Pest Basics

Pest基础

TopicReferenceWhen to Consult
Pest Syntaxpest-basics.mdit(), test(), describe()
Datasetspest-datasets.mdData providers, hooks
Architecturepest-arch.mdarch() tests
主题参考文档适用场景
Pest语法pest-basics.mdit()、test()、describe() 语法使用
数据集pest-datasets.md数据提供者、钩子使用
架构测试pest-arch.mdarch() 测试编写

HTTP Testing

HTTP测试

TopicReferenceWhen to Consult
Requestshttp-requests.mdGET, POST, headers
JSON APIhttp-json.mdAPI assertions
Authenticationhttp-auth.mdactingAs, guards
Assertionshttp-assertions.mdStatus, redirects
主题参考文档适用场景
请求处理http-requests.mdGET、POST、请求头设置
JSON APIhttp-json.mdAPI断言验证
身份认证http-auth.mdactingAs、守卫使用
断言方法http-assertions.md状态码、重定向验证

Database Testing

数据库测试

TopicReferenceWhen to Consult
Basicsdatabase-basics.mdRefreshDatabase
Factoriesdatabase-factories.mdFactory patterns
Assertionsdatabase-assertions.mdDB assertions
主题参考文档适用场景
基础用法database-basics.mdRefreshDatabase 特性使用
工厂模式database-factories.md工厂类编写与使用
数据库断言database-assertions.md数据库状态验证

Mocking

模拟(Mocking)

TopicReferenceWhen to Consult
Servicesmocking-services.mdMock, spy
Fakesmocking-fakes.mdMail, Queue, Event
HTTP & Timemocking-http.mdHttp::fake, travel
主题参考文档适用场景
服务模拟mocking-services.mdMock、Spy 使用
假对象(Fakes)mocking-fakes.mdMail、Queue、Event 模拟
HTTP与时间模拟mocking-http.mdHttp::fake、travel 方法使用

Other

其他

TopicReferenceWhen to Consult
Consoleconsole-tests.mdArtisan tests
Troubleshootingtroubleshooting.mdCommon errors
主题参考文档适用场景
控制台测试console-tests.mdArtisan 命令测试
故障排查troubleshooting.md常见错误解决

Templates

模板

TemplateWhen to Use
FeatureTest.php.mdHTTP feature test
UnitTest.php.mdService unit test
ArchTest.php.mdArchitecture test
ApiTest.php.mdREST API test
PestConfig.php.mdPest configuration

模板适用场景
FeatureTest.php.mdHTTP功能测试编写
UnitTest.php.md服务单元测试编写
ArchTest.php.md架构测试编写
ApiTest.php.mdREST API测试编写
PestConfig.php.mdPest配置

Quick Reference

快速参考

php
// Feature test
it('creates a post', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->postJson('/api/posts', ['title' => 'Test'])
        ->assertCreated()
        ->assertJsonPath('data.title', 'Test');

    $this->assertDatabaseHas('posts', ['title' => 'Test']);
});

// With dataset
it('validates emails', function (string $email, bool $valid) {
    // test logic
})->with([
    ['valid@test.com', true],
    ['invalid', false],
]);

// Mock facade
Mail::fake();
// ... action ...
Mail::assertSent(OrderShipped::class);

php
// Feature test
it('creates a post', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->postJson('/api/posts', ['title' => 'Test'])
        ->assertCreated()
        ->assertJsonPath('data.title', 'Test');

    $this->assertDatabaseHas('posts', ['title' => 'Test']);
});

// With dataset
it('validates emails', function (string $email, bool $valid) {
    // test logic
})->with([
    ['valid@test.com', true],
    ['invalid', false],
]);

// Mock facade
Mail::fake();
// ... action ...
Mail::assertSent(OrderShipped::class);

Commands

命令

bash
undefined
bash
undefined

Run all tests

Run all tests

php artisan test
php artisan test

Pest directly

Pest directly

./vendor/bin/pest
./vendor/bin/pest

Parallel execution

Parallel execution

./vendor/bin/pest --parallel
./vendor/bin/pest --parallel

Filter by name

Filter by name

./vendor/bin/pest --filter "user can"
./vendor/bin/pest --filter "user can"

Coverage

Coverage

./vendor/bin/pest --coverage --min=80
./vendor/bin/pest --coverage --min=80

Profile slow tests

Profile slow tests

./vendor/bin/pest --profile

---
./vendor/bin/pest --profile

---

Best Practices

最佳实践

DO

✅ 建议

  • Use
    RefreshDatabase
    trait
  • Follow AAA pattern (Arrange-Act-Assert)
  • Name tests descriptively
  • Test one thing per test
  • Use factories for data
  • 使用
    RefreshDatabase
    trait
  • 遵循AAA模式(准备-执行-断言)
  • 给测试起描述性名称
  • 每个测试只验证一个点
  • 使用工厂生成测试数据

DON'T

❌ 避免

  • Create test dependencies
  • Call real external APIs
  • Use production database
  • Skip edge cases
  • 创建测试依赖
  • 调用真实外部API
  • 使用生产数据库
  • 忽略边缘情况