⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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 方法。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 90 篇
0 完成
🔥 0