Laravel内置PHPUnit支持,提供单元测试和功能测试两类,通过TestCase基类和辅助方法如assertDatabaseHas、RefreshDatabase等简化测试流程,可使用php artisan test命令运行测试,建议从简单类测试入手逐步覆盖业务逻辑。

在 Laravel 项目中写单元测试非常方便,因为框架本身就集成了 PHPUnit,并提供了丰富的辅助方法来简化测试流程。如果你刚接触 Laravel 测试,可以从基础的单元测试和功能测试开始。
PHPUnit 是 PHP 的标准单元测试框架。Laravel 默认使用 PHPUnit 来运行测试,测试文件放在 tests 目录下。Laravel 提供了两种主要类型的测试:
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);
}
}
运行这个测试:
php artisan test --filter=MathServiceTest
如果看到绿色的“OK”,说明测试通过了。
功能测试更贴近实际使用场景。比如测试用户注册接口是否正常工作:
// 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',
]);
}
}
几点说明:
在测试中,断言是验证结果的核心。常见的有:
Laravel 提供了 Artisan 命令来运行测试:
你也可以只运行单元测试或功能测试:
php artisan test --parallel --group=Unit
以上就是Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号