使用Composer安装PHPUnit只需运行composer require --dev phpunit/phpunit,并在项目根目录创建phpunit.xml配置文件,指定bootstrap、testsuites和filter,然后在tests目录下编写测试类,最后通过./vendor/bin/phpunit运行测试即可完成单元测试环境搭建。

使用 Composer 安装和配置 PHPUnit 是 PHP 项目中进行单元测试的标准做法。整个过程简单清晰,只需几步即可完成。
安装 PHPUnit
在项目根目录下打开终端,运行以下命令通过 Composer 安装 PHPUnit:
composer require --dev phpunit/phpunit这个命令会将 PHPUnit 作为开发依赖安装到项目中,不会影响生产环境。安装完成后,PHPUnit 可执行文件会被放在 vendor/bin/phpunit。
创建基本配置文件
PHPUnit 使用 phpunit.xml 或 phpunit.xml.dist 作为配置文件。在项目根目录创建 phpunit.xml 文件:
立即学习“PHP免费学习笔记(深入)”;
<?xml version="1.0" encoding="UTF-8"?><phpunit
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
stopOnFailure="false"
>
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
说明:
- bootstrap 指向自动加载文件,确保测试时能加载项目类。
- testsuites 定义测试文件存放目录,这里指定 tests 目录下以 Test.php 结尾的文件为测试用例。
- filter/whitelist 用于代码覆盖率分析,包含 src 目录下的源码。
编写一个简单测试
创建 tests/ExampleTest.php 文件:
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testTrueAssertsToTrue()
{
$this->assertTrue(true);
}
}
这个测试会通过,用于验证 PHPUnit 是否正常工作。
运行测试
执行以下命令运行所有测试:
./vendor/bin/phpunit你会看到类似“OK (1 test, 1 assertion)”的输出,表示测试成功。
你也可以指定运行某个测试文件:
./vendor/bin/phpunit tests/ExampleTest.php基本上就这些。Composer 安装 PHPUnit 简单可靠,配合配置文件可快速搭建测试环境。后续只需在 tests 目录下添加更多测试类即可。不复杂但容易忽略的是确保自动加载和目录结构匹配配置。











