如何为我的Composer包编写自动化测试并集成CI?(GitHub Actions示例)

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

如何为我的Composer包编写自动化测试并集成CI?(GitHub Actions示例)-第1张图片-佛山资讯网

为 Composer 包编写自动化测试并接入 CI,核心是三件事:写好 PHPUnit 测试、配置 phpunit.xmlphpunit.xml.dist、在 GitHub Actions 中定义 PHP 测试工作流。下面分步说明。

1. 确保项目结构支持测试

标准 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。

2. 编写可运行的测试用例

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,保证命名空间解析正确。

3. 配置 PHPUnit 并验证本地运行

在项目根目录创建 phpunit.xml.dist

标签: php js bootstrap git json composer github ubuntu curl

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~