首先安装composer并运行composer require –dev phpunit/phpunit,然后在项目根目录创建phpunit.xml配置文件设置bootstrap、colors和tests目录,接着创建tests目录并编写测试类,最后通过vendor/bin/phpunit运行测试。

要通过 Composer 安装和配置 PHPUnit,只需几个简单步骤即可完成。Composer 是 PHP 的依赖管理工具,能轻松安装 PHPUnit 并自动处理依赖关系。
使用 Composer 安装 PHPUnit
确保系统已安装 Composer。若未安装,请先前往 getcomposer.org 下载并安装。
在项目根目录打开终端,运行以下命令来安装 PHPUnit:
- composer require --dev phpunit/phpunit
该命令会将 PHPUnit 作为开发依赖添加到项目中,并写入 composer.json 文件。安装完成后,PHPUnit 可通过 vendor/bin/phpunit 执行。
立即学习“PHP免费学习笔记(深入)”;
创建 phpunit.xml 配置文件
在项目根目录创建 phpunit.xml 或 phpunit.xml.dist 文件,用于定义测试配置。基本配置示例如下:
                  <?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=”Test.php”>tests</directory>
         </testsuite>
     </testsuites>
 </phpunit> 
说明:
 – bootstrap 指定自动加载文件,确保类能正确加载。
 – colors 启用彩色输出,便于查看测试结果。
 – directory 定义测试文件存放路径,此处为 tests 目录,且文件以 Test.php 结尾。
编写并运行测试
在项目中创建 tests 目录,并添加测试类。例如创建 ExampleTest.php:
<?php
use PHPUnitFrameworkTestCase;
 class ExampleTest extends TestCase
 {
     public function testTrueAssertsToTrue()
     {
         $this->assertTrue(true);
     }
 } 
保存后,在终端运行:
- vendor/bin/phpunit
PHPUnit 将自动发现并执行测试,输出结果会显示测试通过或失败信息。
基本上就这些。通过 Composer 安装 PHPUnit 简单可靠,配合配置文件可快速搭建本地测试环境。不复杂但容易忽略的是确保 autoload 和测试路径设置正确。


