Laravel内置PHPUnit支持,提供单元测试与功能测试。1. 单元测试使用php artisan make:test --unit创建,用于验证独立组件如方法逻辑;2. 功能测试位于tests/Feature,通过模拟HTTP请求、数据库断言等验证应用行为,如用户注册流程;3. 使用RefreshDatabase确保测试数据隔离;4. 支持模拟门面、认证用户、表单错误及API测试;5. 运行测试用php artisan test --filter=Unit/Feature。体系完善,易于上手。

在 Laravel 中进行单元测试和功能测试非常方便,框架内置了对 PHPUnit 的支持,并提供了丰富的辅助方法来模拟请求、数据库操作和响应断言。下面分别介绍如何进行单元测试和功能测试。
单元测试(Unit Testing)
单元测试用于测试应用中的独立组件,比如一个类、一个方法或一个服务,确保它们在隔离环境下按预期工作。
1. 创建单元测试类使用 Artisan 命令生成测试文件:
php artisan make:test CalculateServiceTest --unit
加上 --unit 会将测试放在 tests/Unit 目录下。
假设你有一个计算服务 CalculateService:
// app/Services/CalculateService.php
namespace App\Services;
class CalculateService
{
public function add($a, $b)
{
return $a + $b;
}
}
对应的测试代码:
// tests/Unit/CalculateServiceTest.php
namespace Tests\Unit;
use Tests\TestCase;
use App\Services\CalculateService;
class CalculateServiceTest extends TestCase
{
public function test_add_method_returns_sum_of_two_numbers()
{
$service = new CalculateService();
$result = $service->add(2, 3);
$this->assertEquals(5, $result);
}
}
3. 运行单元测试执行以下命令运行所有单元测试:
php artisan test --filter=Unit
或直接运行 PHPUnit:
./vendor/bin/phpunit --filter=Unit
功能测试(Feature Testing)
功能测试关注的是应用程序的行为,比如路由、控制器、中间件、表单提交等端到端流程。
1. 创建功能测试Laravel 默认将功能测试放在 tests/Feature 目录。创建一个用户注册测试:
注意:请将此程序放在网站根目录下运行。若没有IIS,请直接运行根目录下的 测试.exe 进行本地测试。 基本功能表基本设置:后台可修改联系方式,网站信息。管 理 员:可新增管理员。自定义导航:新增修改导航菜单、菜单排序等。单页管理:单页面新增关键词和描述等。新闻增加:新闻可设置标题、新闻分类、添加内容等。新闻管理:可分类查看新闻、修改新闻、删除新闻等。产品管理:产品增加二级分类,产品略缩图、产品
php artisan make:test UserRegistrationTest
测试用户注册接口是否正常工作:
// tests/Feature/UserRegistrationTest.php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserRegistrationTest extends TestCase
{
use RefreshDatabase; // 每次测试后重置数据库
public function test_user_can_register()
{
$response = $this->post('/register', [
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => 'password',
'password_confirmation' => 'password',
]);
$response->assertRedirect('/home');
$this->assertDatabaseHas('users', [
'email' => 'john@example.com'
]);
}
}
3. 模拟 HTTP 请求Laravel 提供了多种 HTTP 测试方法:
-
$this->get('/profile')— 发送 GET 请求 -
$this->post('/login', $data)— 发送 POST 请求 -
$this->json('POST', '/api/user', ['name' => 'John'])— 发送 JSON 请求
还可以断言响应状态、内容、重定向等:
$response->assertStatus(200)$response->assertSee('Welcome')$response->assertJson(['success' => true])
使用 RefreshDatabase trait 可在测试中安全操作数据库:
use Illuminate\Foundation\Testing\RefreshDatabase;
它会在迁移一次数据库后,用事务回滚每次测试的变更,提升性能。
5. 运行功能测试运行所有功能测试:
php artisan test --filter=Feature
或运行特定测试类:
php artisan test Tests/Feature/UserRegistrationTest
常用测试技巧
-
模拟门面(Facades):如 Mail、Event,使用
Mail::fake()避免真实发送。 -
认证用户:
$this->actingAs($user)模拟登录用户。 -
验证表单错误:
$response->assertSessionHasErrors('email')检查是否返回了表单错误。 -
测试 API:结合
json()方法和assertJson断言结构。
基本上就这些。Laravel 的测试体系集成良好,只要熟悉 PHPUnit 和框架提供的测试辅助方法,就能高效写出可靠的测试用例。不复杂但容易忽略。









