文档授权验证

请输入授权码后查看文档内容

Skip to content

PHPUnit 单元测试操作指南

1. 执行命令

1.1 运行全部测试

Linux/Mac:

bash
./vendor/bin/phpunit

或:

bash
php vendor/bin/phpunit

Windows:

powershell
vendor\bin\phpunit

1.2 运行指定测试文件

bash
php vendor/bin/phpunit tests/ExampleTest.php

1.3 按测试方法过滤

bash
php vendor/bin/phpunit --filter testAdd

1.4 按测试类过滤

bash
php vendor/bin/phpunit --filter ExampleTest

2. 测试目录与命名建议

推荐目录结构:

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.php

4. 常用断言

  • 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/phpunit

5.2 Permission denied(Linux)

给执行权限:

bash
chmod +x vendor/bin/phpunit

然后执行:

bash
./vendor/bin/phpunit

5.3 vendor/bin/phpunit: No such file or directory

通常是依赖未安装:

bash
composer install

6. 推荐团队执行流程

  1. 拉取最新代码并安装依赖
  2. 新功能开发前先运行一次全量测试
  3. 新增功能必须补充对应测试
  4. 提交前至少运行相关测试文件
  5. 合并前在 CI 或服务器上运行全量测试

Released under the Apache-2.0 License.