Pest 是 Laravel 中基于 PHPUnit 的现代测试框架,通过简洁的函数式语法和 DSL 减少样板代码。使用 composer require --dev pestphp/pest pestphp/pest-plugin-laravel 安装后,运行 php artisan pest:install 初始化,自动生成目录结构并集成 Laravel 测试辅助方法。相比 PHPUnit 需定义类和方法,Pest 用 it() 直接描述用例,如 it('returns homepage', function () { get('/')->assertStatus(200); });,更轻量直观。支持 describe() 组织相关测试,提升逻辑可读性;通过 uses() 在 tests/Pest.php 中全局指定基类,实现自动继承;利用 with() 提供数据集,生成多组数据驱动测试;使用 beforeEach() 在每个测试前执行初始化操作,共享上下文。整体上,Pest 以低冗余、高表达的风格让测试编写更愉悦高效。

在 Laravel 项目中,Pest 是一个基于 PHPUnit 的现代测试框架,语法更简洁、可读性更强,让编写测试变得更直观和愉悦。相比传统 PHPUnit 写法,Pest 使用函数式风格和 DSL(领域特定语言),大幅减少了样板代码,让你专注于测试逻辑本身。
要在 Laravel 项目中使用 Pest,首先通过 Composer 安装:
composer require --dev pestphp/pest pestphp/pest-plugin-laravel
安装完成后,运行以下命令初始化 Pest:
php artisan pest:install
这会创建 tests/Pest.php 和测试目录结构,并自动配置 Laravel 插件,使你可以直接使用 Laravel 提供的测试辅助方法,如 get、post、actingAs 等。
以一个简单的路由测试为例,对比 PHPUnit 与 Pest 的写法差异:
PHPUnit 写法:use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_it_returns_homepage()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}it('returns homepage', function () {
$response = get('/');
$response->assertStatus(200);
});Pest 中无需定义类或方法,使用 it() 函数描述测试用例,内部可以直接调用 Laravel 的测试辅助函数,代码更轻量、语义更清晰。
当需要为同一功能编写多个测试时,可以使用 test 或 it 配合 describe 来组织逻辑:
describe('User Authentication', function () {
it('can login with valid credentials', function () {
$user = User::factory()->create([
'password' => bcrypt($password = 'secret'),
]);
post('/login', [
'email' => $user->email,
'password' => $password,
])->assertRedirect('/dashboard');
$this->assertAuthenticated();
});
it('cannot login with invalid password', function () {
$user = User::factory()->create([
'password' => bcrypt('secret'),
]);
post('/login', [
'email' => $user->email,
'password' => 'wrong',
])->assertSessionHasErrors('email');
});
});describe 块帮助归类相关测试,提升可读性,类似 RSpec 或 Jest 的风格。
Pest 支持 uses() 函数来指定测试文件使用的基类、数据提供者或 Trait。例如,在 Feature 测试中自动使用 TestCase:
uses(\Tests\TestCase::class)->in('Feature');这句通常写在 tests/Pest.php 中,表示所有放在 Feature 目录下的测试都会自动继承 TestCase,无需每个文件重复 use。
Pest 支持简洁的数据提供方式:
it('has invalid email format', function ($email) {
post('/register', ['email' => $email])
->assertSessionHasErrors('email');
})->with([
'invalid-email',
'@missinghost',
'plainaddress',
]);with() 方法传入测试数据集,Pest 会为每条数据生成独立的测试用例,输出中也会清晰显示每组输入的结果。
若需在每个测试前执行某些逻辑,可用 beforeEach:
beforeEach(function () {
$this->user = User::factory()->create();
});
it('can view profile', function () {
$this->actingAs($this->user)->get('/profile')
->assertOk();
});$this 在闭包中依然可用,适合存放共享实例。
以上就是Laravel如何使用Pest进行更优雅的测试_Laravel Pest测试框架写法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号