在 composer.JSon 的 scripts 中定义 test 命令运行 phpUnit;2. 确保通过 composer require –dev phpunit/phpunit 安装;3. 可自定义配置路径、分组测试或结合 Composer 事件自动执行。

要在 Composer 脚本中触发 PHPUnit 测试,只需在 composer.json 中定义一个自定义脚本,绑定到 PHPUnit 的执行命令即可。Composer 支持通过 "scripts" 字段运行各种生命周期钩子或自定义命令,利用这一点可以轻松集成测试流程。
配置 scripts 部分运行 PHPUnit
确保你已经通过 Composer 安装了 PHPUnit(推荐作为开发依赖):
composer require –dev phpunit/phpunit
然后在 composer.json 文件中添加一个脚本,例如命名为 test:
{ "scripts": { “test”: “phpunit” } }
这样就可以通过以下命令运行测试:
立即学习“PHP免费学习笔记(深入)”;
composer test
自定义 PHPUnit 配置路径或参数
如果你的 phpunit.xml 配置文件不在根目录,或者想传递额外参数,可以在脚本中指定:
{ "scripts": { “test”: “phpunit –configuration tests/phpunit.xml –coverage-text” } }
也可以拆分为多个脚本,比如分别运行单元测试和功能测试:
{ "scripts": { “test:unit”: “phpunit –group unit”, “test:integration”: “phpunit –group integration”, “test:all”: “@test:unit && @test:integration” } }
结合其他 Composer 事件自动运行测试
你还可以让测试在某些 Composer 事件发生时自动执行,比如安装依赖后:
{ "scripts": { “post-install-cmd”: “composer test” } }
或者在代码变更后自动测试(配合工具如 inotify 或开发监听器),虽然 Composer 本身不支持文件监听,但脚本可被外部工具调用。
基本上就这些。只要 PHPUnit 可执行文件在 vendor/bin 下(默认位置),phpunit 命令就能被正确识别。如果遇到命令未找到的问题,尝试使用 ./vendor/bin/phpunit 明确路径。