安装 phpUnit:运行 composer require –dev phpunit/phpunit 添加为开发依赖;2. 创建配置文件:在根目录添加 phpunit.xml,指定自动加载、测试目录等;3. 创建测试目录与用例:新建 tests/ 目录并编写继承 TestCase 的测试类;4. 运行测试:执行 ./vendor/bin/phpunit 启动测试。

为基于 Composer 的 PHP 包配置 PHPUnit 测试,主要是通过安装 PHPUnit 作为开发依赖,并创建必要的配置文件和测试用例。下面是一个清晰的步骤说明,帮助你快速搭建测试环境。
安装 PHPUnit 作为开发依赖
在你的包根目录下运行以下命令,使用 Composer 安装 PHPUnit:
composer require –dev phpunit/phpunit
这会将 PHPUnit 添加到 require-dev 部分,并自动安装到 vendor/bin/ 目录下。
创建 phpunit.xml 配置文件
在项目根目录创建 phpunit.xml 或 phpunit.xml.dist 文件,用于定义测试的自动加载、测试目录、引导文件等。
立即学习“PHP免费学习笔记(深入)”;
示例配置:
<?xml version=”1.0″ encoding=”UTF-8″?>
<phpunit
bootstrap=”vendor/autoload.php”
colors=”true”
convertErrorsToExceptions=”true”
convertNoticesToExceptions=”true”
convertWarningsToExceptions=”true”>
<testsuites>
<testsuite name=”application Test Suite”>
<Directory suffix=”.php”>tests/</directory>
</testsuite>
</testsuites>
</phpunit>
这个配置告诉 PHPUnit:
- 使用 Composer 自动生成的自动加载器
- 从 tests/ 目录加载以 .php 结尾的测试文件
- 开启彩色输出和异常转换
创建测试目录和测试用例
创建一个 tests/ 目录,并添加你的第一个测试类。
例如:tests/ExampleTest.php
<?php
use PHPUnitFrameworkTestCase;
class ExampleTest extends TestCase
{
public function testTrueIsTrue()
{
$this->assertTrue(true);
}
}
确保类名与文件名一致,且继承 TestCase。
运行测试
使用以下命令运行测试:
./vendor/bin/phpunit
PHPUnit 会自动读取 phpunit.xml 配置并执行所有 tests/ 下的测试用例。
你可以添加更多选项,如:
- –coverage-html 生成代码覆盖率报告
- tests/ExampleTest.php 只运行某个测试文件
基本上就这些。配置完成后,每次修改代码都可以通过 ./vendor/bin/phpunit 快速验证功能正确性。


