首页 > php框架 > Laravel > 正文

Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门

裘德小鎮的故事
发布: 2025-12-03 07:21:24
原创
133人浏览过
Laravel内置PHPUnit支持,提供单元测试和功能测试两类,通过TestCase基类和辅助方法如assertDatabaseHas、RefreshDatabase等简化测试流程,可使用php artisan test命令运行测试,建议从简单类测试入手逐步覆盖业务逻辑。

laravel怎么写单元测试_phpunit在laravel项目中的基础测试入门

在 Laravel 项目中写单元测试非常方便,因为框架本身就集成了 PHPUnit,并提供了丰富的辅助方法来简化测试流程。如果你刚接触 Laravel 测试,可以从基础的单元测试和功能测试开始。

什么是 PHPUnit 和 Laravel 中的测试

PHPUnit 是 PHP 的标准单元测试框架。Laravel 默认使用 PHPUnit 来运行测试,测试文件放在 tests 目录下。Laravel 提供了两种主要类型的测试:

  • 单元测试(Unit Tests):测试单个函数、类或方法的逻辑,不涉及数据库、路由或外部服务。
  • 功能测试(Feature Tests):测试整个请求响应流程,比如访问某个路由是否返回正确页面或 JSON 数据。

Laravel 为这两类测试都提供了基类:Tests\TestCase,所有测试类都会继承它。

创建第一个单元测试

假设你有一个简单的数学工具类,用来做加法运算:

立即学习PHP免费学习笔记(深入)”;

// app/Services/MathService.php
namespace App\Services;

class MathService
{
    public function add($a, $b)
    {
        return $a + $b;
    }
}
登录后复制

你可以为这个类写一个单元测试:

// tests/Unit/MathServiceTest.php
namespace Tests\Unit;

use Tests\TestCase;
use App\Services\MathService;

class MathServiceTest extends TestCase
{
    public function test_it_can_add_two_numbers()
    {
        $math = new MathService();
        $result = $math->add(3, 5);

        $this->assertEquals(8, $result);
    }
}
登录后复制

运行这个测试:

Superflow Rewrite
Superflow Rewrite

AI辅助高效网站设计、协作、注释工具,迭代和发布网站的最快方式

Superflow Rewrite 58
查看详情 Superflow Rewrite
php artisan test --filter=MathServiceTest
登录后复制

如果看到绿色的“OK”,说明测试通过了。

测试 Laravel 功能:例如用户注册

功能测试更贴近实际使用场景。比如测试用户注册接口是否正常工作:

// 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('/dashboard');
        $this->assertDatabaseHas('users', [
            'name' => 'John Doe',
            'email' => 'john@example.com',
        ]);
    }
}
登录后复制

几点说明:

  • RefreshDatabase:确保测试不会污染真实数据,推荐用于涉及数据库的操作。
  • $this->post():模拟 POST 请求。
  • assertRedirect:断言跳转到指定路径。
  • assertDatabaseHas:断言数据库中存在某条记录。

常用断言方法

在测试中,断言是验证结果的核心。常见的有:

  • $this->assertEquals($expected, $actual):判断两个值是否相等。
  • $this->assertTrue($condition):判断是否为 true。
  • $response->assertStatus(200):检查 HTTP 状态码
  • $response->assertSee('text'):检查响应内容是否包含某文本。
  • $response->assertJson(['key' => 'value']):检查 JSON 响应结构。
  • $this->assertNull($value):判断是否为 null。

运行测试

Laravel 提供了 Artisan 命令来运行测试:

  • php artisan test:运行所有测试。
  • php artisan test --filter=MathServiceTest:运行指定测试类或方法。
  • php artisan test --parallel:并行运行测试(Laravel 9+),加快速度。

你也可以只运行单元测试或功能测试:

php artisan test --parallel --group=Unit
登录后复制

小建议

  • 测试类命名规范:以测试类型开头,如 UserTestMathServiceTest
  • 测试方法名尽量描述行为,如 test_user_cannot_view_unpublished_post
  • 使用 RefreshDatabase 避免数据残留。
  • 不要测试第三方包逻辑,只测试自己的代码。
基本上就这些。Laravel 的测试系统开箱即用,配合 PHPUnit 写起来很顺手。从简单类测试入手,再逐步覆盖控制器、API 和业务逻辑,能显著提升代码质量。

以上就是Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号