400 0867 457

NEWS/新闻

分享你我感悟

您当前位置> 主页 > 新闻 > 技术开发

Laravel怎么进行单元测试和功能测试

发表时间:2025-11-20 00:00:00

文章作者:下次还敢

浏览次数:

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 目录下。

2. 编写测试示例

假设你有一个计算服务 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 目录。创建一个用户注册测试:

php artisan make:test UserRegistrationTest

2. 编写功能测试示例

测试用户注册接口是否正常工作:

// 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])
4. 数据库测试技巧

使用 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 和框架提供的测试辅助方法,就能高效写出可靠的测试用例。不复杂但容易忽略。

相关案例查看更多