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 的支持,并提供了丰富的辅助方法来模拟请求、数据库操作和响应断言。下面分别介绍如何进行单元测试和功能测试。
单元测试用于测试应用中的独立组件,比如一个类、一个方法或一个服务,确保它们在隔离环境下按预期工作。
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);
}
}
执行以下命令运行所有单元测试:
php artisan test --filter=Unit
或直接运行 PHPUnit:
./vendor/bin/phpunit --filter=Unit
功能测试关注的是应用程序的行为,比如路由、控制器、中间件、表单提交等端到端流程。
1. 创建功能测试Laravel 默认将功能测试放在 tests/Feature 目录。创建一个用户注册测试:
本文档主要讲述的是WebSphere MQ传输环境搭建和测试;主要介绍:MQ核心组件简介、MQ环境的搭建以及通过编写简单的程序对MQ进行测试,希望能起到抛砖引玉的作用。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
0
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'
]);
}
}
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
Mail::fake() 避免真实发送。$this->actingAs($user) 模拟登录用户。$response->assertSessionHasErrors('email') 检查是否返回了表单错误。json() 方法和 assertJson 断言结构。基本上就这些。Laravel 的测试体系集成良好,只要熟悉 PHPUnit 和框架提供的测试辅助方法,就能高效写出可靠的测试用例。不复杂但容易忽略。
以上就是Laravel怎么进行单元测试和功能测试的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号