PHPUnit 单元测试操作指南
1. 执行命令
1.1 运行全部测试
Linux/Mac:
bash
./vendor/bin/phpunit或:
bash
php vendor/bin/phpunitWindows:
powershell
vendor\bin\phpunit1.2 运行指定测试文件
bash
php vendor/bin/phpunit tests/ExampleTest.php1.3 按测试方法过滤
bash
php vendor/bin/phpunit --filter testAdd1.4 按测试类过滤
bash
php vendor/bin/phpunit --filter ExampleTest2. 测试目录与命名建议
推荐目录结构:
text
├─ app/
├─ tests/
│ ├─ Unit/
│ └─ Feature/
└─ vendor/命名建议:
- 文件名:
*Test.php - 类名:
*Test - 方法名:
test*(或使用#[Test]特性)
3. 最小测试示例
php
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class ExampleTest extends TestCase
{
public function testAdd(): void
{
$this->assertSame(4, 2 + 2);
}
}将该文件放到 tests/ExampleTest.php 后执行:
bash
php vendor/bin/phpunit tests/ExampleTest.php4. 常用断言
assertSame($expected, $actual):值与类型都相同assertEquals($expected, $actual):值相同(允许类型转换)assertTrue($value)/assertFalse($value)assertNull($value)/assertNotNull($value)assertCount($n, $array)expectException(ExceptionClass::class):断言异常
5. 常见问题排查
5.1 Could not open input file: vendorbinphpunit
原因:路径写错,少了 /。
错误示例:
bash
php vendorbinphpunit正确示例:
bash
php vendor/bin/phpunit5.2 Permission denied(Linux)
给执行权限:
bash
chmod +x vendor/bin/phpunit然后执行:
bash
./vendor/bin/phpunit5.3 vendor/bin/phpunit: No such file or directory
通常是依赖未安装:
bash
composer install6. 推荐团队执行流程
- 拉取最新代码并安装依赖
- 新功能开发前先运行一次全量测试
- 新增功能必须补充对应测试
- 提交前至少运行相关测试文件
- 合并前在 CI 或服务器上运行全量测试
