PHP 单元测试
掌握 PHPUnit 单元测试框架,编写测试用例确保代码质量。 · 难度:入门 · +15XP
单元测试基础
单元测试是测试最小代码单元(如函数、方法)的行为,PHPUnit 是 PHP 最流行的测试框架。
安装 PHPUnit
使用 Composer:composer require --dev phpunit/phpunit
编写测试类
use PHPUnit\Framework\TestCase;
class MathTest extends TestCase {
public function testAddition() {
$result = 1 + 1;
$this->assertEquals(2, $result);
}
public function testDivisionByZero() {
$this->expectException(DivisionByZeroError::class);
$result = 1 / 0;
}
}
常用断言
| 断言方法 | 用途 |
|---|---|
| assertEquals | 判断相等 |
| assertTrue | 判断为真 |
| assertNull | 判断为 null |
| assertInstanceOf | 判断类型 |
数据提供器
public function additionProvider(): array {
return [
[1, 1, 2],
[0, 0, 0],
[-1, 1, 0],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('additionProvider')]
public function testAdd(int $a, int $b, int $expected) {
$this->assertEquals($expected, $a + $b);
}
练习提示
为下面的 Calculator 类编写测试用例,测试 add 和 divide 方法。