Laravel 自动化测试实战:用 Pest 写 Feature 测试与工厂造数

test12026-09-214 次阅读

为什么用 Pest 写测试

Laravel 自带的 PHPUnit 写法偏样板。Pest 用更接近自然语言的 it() 描述用例,配合 Laravel 的测试断言与模型工厂,写一条接口测试只需几行。测试能保证重构不破坏既有行为,是后端工程的底线。

准备模型工厂

工厂集中定义测试数据的默认形态,调用时再用 state 覆写字段,避免在用例里重复手写数组。

// database/factories/PostFactory.php
namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    protected $model = Post::class;

    public function definition(): array
    {
        return [
            'title' => fake()->sentence(),
            'body'  => fake()->paragraph(),
        ];
    }
}

写一个 Feature 测试

用 RefreshDatabase 保证每个用例在干净库上运行。actingAs 模拟登录,postJson 打接口,断言状态码与数据库状态一致。

// tests/Feature/PostTest.php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('可以创建帖子', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)->postJson('/api/posts', [
        'title' => 'Hello',
        'body'  => 'World',
    ]);

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

it('未登录不能创建帖子', function () {
    $this->postJson('/api/posts', [
        'title' => 'Hello',
        'body'  => 'World',
    ])->assertUnauthorized();
});

运行与工程建议

执行 ./vendor/bin/pest 即可看到每个 it 用例的通过情况。建议把测试接入 CI,每次提交自动跑。

  • 只读测试用 LazilyRefreshDatabase 提升速度,写操作测试用 RefreshDatabase。
  • 多个用例需要同一份前置数据时,用 beforeEach 统一准备。
  • 断言优先用框架提供的 assertCreated、assertUnauthorized,比手写状态码更易读。
  • 工厂只放通用默认,具体差异在用例里用 ->state() 或覆盖字段表达。
T

test1

文章作者

为什么用 Pest 写测试 Laravel 自带的 PHPUnit 写法偏样板。Pest 用更接近自然语言的 it()...

分类
技术
发布时间
2026-09-21
字数
约 1537 字
阅读
4 次