PHP 测试覆盖率报告

wen PHP项目 1

本文目录导读:

PHP 测试覆盖率报告

  1. 工具选择
  2. 配置Xdebug
  3. phpunit.xml 配置
  4. 运行测试生成报告
  5. 使用 PCOV(更快)
  6. 覆盖率指标解释
  7. 自定义覆盖率测试
  8. 集成到 CI/CD
  9. 覆盖率检查
  10. 优化覆盖率的方法
  11. 常用命令行参数
  12. 最佳实践

我来为您介绍如何生成和分析PHP测试覆盖率报告。

工具选择

PHPUnit + Xdebug(最常用)

# 安装Xdebug
pecl install xdebug
# 安装PHPUnit
composer require --dev phpunit/phpunit

或者使用 PCOV(更轻量)

pecl install pcov
composer require --dev phpunit/phpunit

配置Xdebug

php.ini 配置

[xdebug]
xdebug.mode=coverage
xdebug.start_with_request=yes
xdebug.output_dir=/tmp/xdebug

或使用环境变量(推荐)

XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-text

phpunit.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         failOnWarning="true">
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory suffix=".php">./src</directory>
        </include>
        <exclude>
            <directory>./src/Exceptions</directory>
            <file>./src/config.php</file>
        </exclude>
    </source>
    <coverage>
        <report>
            <html outputDirectory="coverage-report" lowUpperBound="50" highLowerBound="90"/>
            <text outputFile="php://stdout" showUncoveredFiles="true"/>
            <clover outputFile="coverage.xml"/>
            <xml outputDirectory="build/coverage-xml"/>
            <crap4j outputDirectory="build/crap4j"/>
        </report>
    </coverage>
</phpunit>

运行测试生成报告

生成HTML报告

./vendor/bin/phpunit --coverage-html ./coverage-report

生成文本报告

./vendor/bin/phpunit --coverage-text

生成多种格式

./vendor/bin/phpunit \
  --coverage-html ./coverage-report \
  --coverage-xml ./coverage-xml \
  --coverage-clover ./coverage.xml \
  --coverage-text

使用 PCOV(更快)

# 安装
pecl install pcov
# 运行
php -d pcov.enabled=1 ./vendor/bin/phpunit --coverage-html coverage-report

覆盖率指标解释

三个主要指标:

  • Line Coverage(行覆盖率):代码行的执行比例
  • Method Coverage(方法覆盖率):方法被调用的比例
  • Branch Coverage(分支覆盖率):条件分支(if/else)的执行比例

示例文本报告格式:

Code Coverage Report:
   Summary:
    Classes: 89.23% (58/65)
    Methods: 91.20% (327/358)
    Lines:   88.45% (1542/1743)

自定义覆盖率测试

<?php
use PHPUnit\Framework\TestCase;
class MathTest extends TestCase
{
    public function testAdd(): void
    {
        $math = new Math();
        $this->assertEquals(4, $math->add(2, 2));
    }
    /**
     * @covers Math::subtract
     * @covers Math::multiply
     */
    public function testOtherMethods(): void
    {
        $math = new Math();
        $this->assertEquals(0, $math->subtract(2, 2));
        $this->assertEquals(4, $math->multiply(2, 2));
    }
}

集成到 CI/CD

GitHub Actions 示例

name: PHP Tests
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: '8.2'
        coverage: xdebug
        tools: composer
    - name: Install dependencies
      run: composer install --prefer-dist
    - name: Run tests with coverage
      run: |
        XDEBUG_MODE=coverage ./vendor/bin/phpunit \
          --coverage-clover coverage.xml
    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml

覆盖率检查

设置最低覆盖率要求

# 使用文本报告的最后几行检查
./vendor/bin/phpunit --coverage-text | grep "Lines:" | awk '{print $3}' | tr -d '%' | awk '{if ($1 < 80) exit 1}'

使用CI环境变量

phpunit --coverage-text --log-junit test-results.xml

优化覆盖率的方法

排除不必要的文件

<source>
    <exclude>
        <directory>./src/Resources</directory>
        <file>./src/register.php</file>
    </exclude>
</source>

使用ignore注释

class User
{
    // @codeCoverageIgnoreStart
    private function debugInfo()
    {
        echo "调试信息";
    }
    // @codeCoverageIgnoreEnd
}

测试分组

<?php
use PHPUnit\Framework\TestCase;
class DatabaseTest extends TestCase
{
    /**
     * @group integration
     * @covers Database::connect
     */
    public function testConnection(): void
    {
        // 集成测试
    }
}

常用命令行参数

# 只测试特定文件
phpunit tests/UserTest.php
# 只运行特定分组
phpunit --group=unit
# 显示测试执行详细过程
phpunit --testdox
# 调试单个测试
phpunit --filter testSpecificMethod

最佳实践

  1. 目标覆盖率:核心业务逻辑至少80%,基础设施代码不低于60%
  2. 关注高风险代码:优先保证复杂逻辑和关键路径的覆盖
  3. 定期审查:在CI中设置覆盖率门槛,阻止覆盖率下降
  4. 使用工具:结合 SonarQube 或 PHPStorm 的覆盖率工具分析

通过这些方法,您可以全面了解代码的质量和测试覆盖情况,持续改进测试策略。

抱歉,评论功能暂时关闭!