Laravel tdd

From aaione/everything-claude-code-zh · View interactive version

Laravel tdd is an AI agent skill from the GitHub repository aaione/everything-claude-code-zh. Laravel 测试驱动开发,使用 PHPUnit 和 Pest,包括工厂、数据库测试、伪造和覆盖率目标。

How to use this skill

Skill file

Laravel TDD 工作流

使用 PHPUnit 和 Pest 进行 Laravel 应用的测试驱动开发,目标覆盖率 80%+(单元 + 功能)。

何时使用

工作原理

红-绿-重构循环

1) 编写一个失败的测试

2) 实现最小改动使其通过

3) 在保持测试通过的同时重构

测试层级

根据范围选择层级:

数据库策略

将 RefreshDatabase 作为涉及数据库的测试的默认选择:对于支持事务的数据库,它通过静态标志每次测试运行执行一次迁移,并将每个测试包装在事务中;对于 :memory: SQLite 或不支持事务的连接,它会在每个测试前迁移。当数据库结构已迁移且只需要每个测试的回滚时使用 DatabaseTransactions。

测试框架选择

示例

PHPUnit 示例

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class ProjectControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_owner_can_create_project(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->postJson('/api/projects', [
            'name' => 'New Project',
        ]);

        $response->assertCreated();
        $this->assertDatabaseHas('projects', ['name' => 'New Project']);
    }
}

功能测试示例(HTTP 层)

use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class ProjectIndexTest extends TestCase
{
    use RefreshDatabase;

    public function test_projects_index_returns_paginated_results(): void
    {
        $user = User::factory()->create();
        Project::factory()->count(3)->for($user)->create();

        $response = $this->actingAs($user)->getJson('/api/projects');

        $response->assertOk();
        $response->assertJsonStructure(['success', 'data', 'error', 'meta']);
    }
}

Pest 示例

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

use function Pest\Laravel\actingAs;
use function Pest\Laravel\assertDatabaseHas;

uses(RefreshDatabase::class);

test('owner can create project', function () {
    $user = User::factory()->create();

    $response = actingAs($user)->postJson('/api/projects', [
        'name' => 'New Project',
    ]);

    $response->assertCreated();
    assertDatabaseHas('projects', ['name' => 'New Project']);
});

功能测试 Pest 示例(HTTP 层)

use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

use function Pest\Laravel\actingAs;

uses(RefreshDatabase::class);

test('projects index returns paginated results', function () {
    $user = User::factory()->create();
    Project::factory()->count(3)->for($user)->create();

    $response = actingAs($user)->getJson('/api/projects');

    $response->assertOk();
    $response->assertJsonStructure(['success', 'data', 'error', 'meta']);
});

工厂和状态

$user = User::factory()->state(['role' => 'admin'])->create();

数据库测试

持久化测试示例

use App\Models\Project;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class ProjectRepositoryTest extends TestCase
{
    use RefreshDatabase;

    public function test_project_can_be_retrieved_by_slug(): void
    {
        $project = Project::factory()->create(['slug' => 'alpha']);

        $found = Project::query()->where('slug', 'alpha')->firstOrFail();

        $this->assertSame($project->id, $found->id);
    }
}

副作用的伪造

use Illuminate\Support\Facades\Queue;

Queue::fake();

dispatch(new SendOrderConfirmation($order->id));

Queue::assertPushed(SendOrderConfirmation::class);
use Illuminate\Support\Facades\Notification;

Notification::fake();

$user->notify(new InvoiceReady($invoice));

Notification::assertSentTo($user, InvoiceReady::class);

认证测试(Sanctum)

use Laravel\Sanctum\Sanctum;

Sanctum::actingAs($user);

$response = $this->getJson('/api/projects');
$response->assertOk();

HTTP 和外部服务

覆盖率目标

测试命令

测试配置

授权测试

use Illuminate\Support\Facades\Gate;

$this->assertTrue(Gate::forUser($user)->allows('update', $project));
$this->assertFalse(Gate::forUser($otherUser)->allows('update', $project));

Inertia 功能测试

使用 Inertia.js 时,使用 Inertia 测试辅助方法断言组件名和 props。

use App\Models\User;
use Inertia\Testing\AssertableInertia;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class DashboardInertiaTest extends TestCase
{
    use RefreshDatabase;

    public function test_dashboard_inertia_props(): void
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->get('/dashboard');

        $response->assertOk();
        $response->assertInertia(fn (AssertableInertia $page) => $page
            ->component('Dashboard')
            ->where('user.id', $user->id)
            ->has('projects')
        );
    }
}

优先使用 assertInertia 而非原始 JSON 断言,以保持测试与 Inertia 响应一致。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.