为 Composer 包配置自动化测试与 CI 的核心是:编写 PHPUnit 测试、配置 phpunit.xml.dist、在 GitHub Actions 中定义多 PHP 版本测试工作流,确保测试类命名规范、自动加载正确、CI 中声明 dev 依赖。

为 Composer 包编写自动化测试并接入 CI,核心是三件事:写好 PHPUnit 测试、配置 phpunit.xml 或 phpunit.xml.dist、在 GitHub Actions 中定义 PHP 测试工作流。下面分步说明。
标准 Composer 包应包含 src/(源码)、tests/(测试用例)和 composer.json。测试文件通常与源码一一对应,比如 src/Helper.php 对应 tests/HelperTest.php,类名以 Test 结尾,继承 PHPUnitFrameworkTestCase。
安装测试依赖:
composer require --dev phpunit/phpunit ^10
如果使用较新 PHP 版本(如 8.2+),推荐 PHPUnit 10;若需兼容 PHP 7.4,可用 PHPUnit 9。
在 tests/ 下创建测试类,例如 tests/CalculatorTest.php:
<?php
use PHPUnitFrameworkTestCase;
<p>class CalculatorTest extends TestCase
{
public function testAddReturnsCorrectResult(): void
{
$this->assertSame(5, 2 + 3);
}
}
确保 composer.json 中定义自动加载规则,让测试能加载源码:
"autoload": {
"psr-4": {
"MyVendor\MyPackage\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"MyVendor\MyPackage\Tests\": "tests/"
}
}
运行测试前执行:composer dump-autoload,保证命名空间解析正确。
在项目根目录创建 phpunit.xml.dist:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
verbose="true">
<testsuites>
<testsuite name="default">
<directory>tests/</directory>
</testsuite>
</testsuites>
</phpunit>
然后终端执行:./vendor/bin/phpunit。看到绿色 OK 表示测试就绪。
在项目根目录新建 .github/workflows/test.yml:
name: Test Package
<p>on: [push, pull_request]</p><p>jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['8.1', '8.2', '8.3']</p><pre class="brush:php;toolbar:false;">steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: mbstring, xml, curl
coverage: none
- name: Install dependencies
run: composer install --no-interaction --prefer-dist
- name: Run tests
run: vendor/bin/phpunit --testdox该流程会:
--testdox 输出易读的测试报告提交后,GitHub 会自动触发检查,失败时 PR 页面显示红叉,点击可查看详细日志。
不复杂但容易忽略:记得在 composer.json 的 require-dev 中声明 phpunit/phpunit,否则 CI 安装依赖时可能漏掉它;另外,测试类文件名必须以 Test.php 结尾,且类名匹配,否则 PHPUnit 默认扫描不到。
以上就是如何为我的Composer包编写自动化测试并集成CI?(GitHub Actions示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号