Code coverage
suggest changeCode coverage measures which parts of your code ran while the tests ran. It answers "which code do my tests never run?" and points you to the else branch nobody tested or the error path that has never thrown. It does not tell you whether the tests check the right things. A test with no assertions still counts toward coverage.
PHP has no built-in coverage. A driver extension records which lines ran, and php-code-coverage, the library behind PHPUnit's --coverage-* options, turns that data into reports.
The examples use PHP 8.5, PHPUnit 13 (php-code-coverage 14), PCOV 1.0 and Xdebug 3.5. To run coverage in GitHub Actions or GitLab and upload it to a service, see Testing in CI.
Line, branch and path coverage
There are three levels of detail:
- Line coverage: was each executable line run at least once? This is the default and what most people mean by "coverage".
- Branch coverage: was each branch taken? In
$a > 0 ? 'x' : 'y'both outcomes are on one line, so line coverage can't tell whether'y'was ever returned. The same goes for each operand of&&and||. - Path coverage: was each combination of branches through a function run? A function with three independent
ifs has 2 × 2 × 2 = 8 paths. You can take every branch without running every path.
PCOV only supports line coverage. Branch and path coverage need Xdebug.
Coverage drivers: PCOV and Xdebug
| PCOV | Xdebug | |
|---|---|---|
| What it does | coverage only | debugger, profiler, tracing, coverage |
| Line coverage | yes | yes |
| Branch / path coverage | no | yes |
| Speed | close to normal speed | much slower, uses much more memory for branch/path |
| Enable | load the extension | load it and set xdebug.mode=coverage |
Use PCOV for everyday runs and CI. Use Xdebug when you need branch or path coverage, or when it is already installed for debugging (see Xdebug).
Installing:
# PECL (builds from source, needs phpize and a compiler)
pecl install pcov
pecl install xdebug
# Debian/Ubuntu with the ondrej/php packages
sudo apt install php8.5-pcov php8.5-xdebug
# official Docker images
pecl install pcov && docker-php-ext-enable pcov
Then enable them in php.ini (PECL doesn't always do this for you):
extension=pcov
; Xdebug is a Zend extension
zend_extension=xdebug
xdebug.mode=coverage
Check what is loaded:
$ php --ri pcov
pcov
PCOV support => Enabled
PCOV version => 1.0.12
pcov.directory => /home/kjk/shop/src
pcov.exclude => none
pcov.initial.memory => 65336 bytes
pcov.initial.files => 64
$ php -v
PHP 8.5.9 (cli) (built: Jul 30 2026 19:57:02) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.5.9, Copyright (c) Zend Technologies
with Xdebug v3.5.3, Copyright (c) 2002-2026, by Derick Rethans
with Zend OPcache v8.5.9, Copyright (c), by Zend Technologies
Notes:
pcov.directorylimits which files PCOV tracks. When it isn't set, PCOV usessrc/,lib/orapp/if one exists in the current directory, and the current directory otherwise. If your code lives somewhere else (for examplemodule/), coverage will show 0% until you set it:php -d pcov.directory=. vendor/bin/phpunit --coverage-text.- Xdebug only collects coverage when its mode includes
coverage. Setxdebug.mode=coverage(ordebug,coverage) inphp.ini, or set the environment variable for one run:XDEBUG_MODE=coverage vendor/bin/phpunit .... - Don't load both. If both are loaded, PHPUnit uses PCOV, and Xdebug still slows everything down.
- Don't load either in production. They are development and CI tools.
Without a usable driver PHPUnit prints a warning, runs no tests and exits with 1:
$ vendor/bin/phpunit --coverage-text
PHPUnit 13.4.3 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.9
Configuration: /home/kjk/shop/phpunit.xml.dist
There was 1 PHPUnit test runner warning:
1) No code coverage driver available that supports line coverage
No tests executed!
With Xdebug loaded but in the wrong mode, the warning is XDEBUG_MODE=coverage (environment variable) or xdebug.mode=coverage (PHP configuration setting) has to be set.
Telling PHPUnit what your code is
PHPUnit reports coverage only for files listed in the <source> element of phpunit.xml.dist:
<?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"
cacheDirectory=".phpunit.cache"
colors="true">
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
Without <source>, the tests run but you get No filter is configured, code coverage will not be processed instead of a report. For a one-off run without a configuration file, pass the directory on the command line with --coverage-filter src.
Files under <source> that no test loads are still in the report, at 0%. That is what you want: a class with no tests at all should lower the number. You can't hide it by never loading it.
A first report
The code under test:
<?php
declare(strict_types=1);
namespace App;
final class ShippingCalculator
{
public function cost(int $weightGrams, string $country, bool $express = false): int
{
if ($weightGrams <= 0) {
throw new \InvalidArgumentException('Weight must be positive');
}
$cost = $country === 'PL' ? 1000 : 2500;
if ($weightGrams > 5000) {
$cost += intdiv($weightGrams - 5000, 1000) * 200;
}
if ($express) {
$cost *= 2;
}
return $cost;
}
public function isFree(int $orderTotal, bool $member): bool
{
return $orderTotal >= 10000 || ($member && $orderTotal >= 5000);
}
public function label(int $weightGrams, string $country): string
{
return 'Shipping: ' . Money::format($this->cost($weightGrams, $country));
}
}
src/Money.php:
<?php
declare(strict_types=1);
namespace App;
final class Money
{
public static function format(int $cents): string
{
return sprintf('%d.%02d', intdiv($cents, 100), $cents % 100);
}
}
And a first set of tests (MoneyTest has one test for Money::format() and is marked #[CoversClass(Money::class)]):
<?php
declare(strict_types=1);
namespace App\Tests;
use App\Money;
use App\ShippingCalculator;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(ShippingCalculator::class)]
#[UsesClass(Money::class)]
final class ShippingCalculatorTest extends TestCase
{
private ShippingCalculator $calc;
protected function setUp(): void
{
$this->calc = new ShippingCalculator();
}
public function testDomestic(): void
{
$this->assertSame(1000, $this->calc->cost(1200, 'PL'));
}
public function testHeavyInternational(): void
{
$this->assertSame(2900, $this->calc->cost(7500, 'DE'));
}
public function testFreeForLargeOrders(): void
{
$this->assertTrue($this->calc->isFree(12000, false));
}
public function testLabel(): void
{
$this->assertSame('Shipping: 10.00', $this->calc->label(500, 'PL'));
}
}
--coverage-text prints a summary after the test results:
$ vendor/bin/phpunit --coverage-text
PHPUnit 13.4.3 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.9 with PCOV 1.0.12
Configuration: /home/kjk/shop/phpunit.xml.dist
..... 5 / 5 (100%)
Time: 00:00.002, Memory: 22.00 MB
OK (5 tests, 5 assertions)
Code Coverage Report:
2026-10-17 17:30:38
Summary:
Classes: 50.00% (1/2)
Methods: 75.00% (3/4)
Lines: 81.81% (9/11)
App\Money
Methods: 100.00% ( 1/ 1) Lines: 100.00% ( 1/ 1)
App\ShippingCalculator
Methods: 66.66% ( 2/ 3) Lines: 80.00% ( 8/ 10)
How to read it:
- Lines counts executable lines only. Braces, comments,
usestatements and thefunctionline itself don't count, soShippingCalculatorhas 10 lines, not 36. - Methods: a method counts as covered only when all of its lines are covered.
cost()is at 6 of 8 lines, so it doesn't count. - Classes: a class counts as covered only when all of its methods are.
The text report doesn't say which lines were missed. For that, generate the HTML report:
vendor/bin/phpunit --coverage-html build/coverage
Open build/coverage/index.html. It has a directory view with coverage bars and, for each file, the source with every executable line colored: green for covered, red for not covered, yellow for dead code. Hovering over a green line lists the tests that ran it. Here the red lines are the throw (line 11) and $cost *= 2; (line 21): no test passes a zero weight or express: true. The dashboard page (dashboard.html) lists the least covered and the riskiest methods.
Add build/ to .gitignore.
Report formats
| Option | Output |
|---|---|
--coverage-text |
summary on stdout; --coverage-text=build/coverage.txt writes a file |
--only-summary-for-coverage-text |
only the summary, no per-class lines |
--show-uncovered-for-coverage-text |
include classes with 0% coverage in the per-class list |
--coverage-html <dir> |
browsable HTML with highlighted source |
--coverage-clover <file> |
Clover XML, read by Codecov, Coveralls, SonarQube, IDEs |
--coverage-openclover <file> |
OpenClover XML |
--coverage-cobertura <file> |
Cobertura XML (GitLab merge request diffs, Azure DevOps) |
--coverage-crap4j <file> |
CRAP index per method |
--coverage-xml <dir> |
PHPUnit's own XML format (used by Infection mutation testing) |
--coverage-jsonl <dir> |
JSON Lines |
--coverage-php <file> |
serialized coverage data, for merging later with phpcov |
--no-coverage |
ignore the coverage configured in the XML file |
Several report options can be combined in one run. Coverage is collected once and written in every format you ask for.
Instead of typing options, configure the reports in phpunit.xml.dist. They are generated on every run where a driver is available. Use --no-coverage for quick runs:
<coverage includeUncoveredFiles="true"
pathCoverage="false"
ignoreDeprecatedCodeUnits="true">
<report>
<html outputDirectory="build/coverage" lowUpperBound="50" highLowerBound="90"/>
<clover outputFile="build/clover.xml"/>
<text outputFile="php://stdout" showOnlySummary="true"/>
</report>
</coverage>
lowUpperBound and highLowerBound set where the HTML report switches between red, yellow and green. ignoreDeprecatedCodeUnits leaves out classes and methods marked @deprecated.
To leave generated or bootstrap files out of the report, add <exclude> to <source>:
<source>
<include>
<directory suffix=".php">src</directory>
</include>
<exclude>
<directory>src/Generated</directory>
<file>src/bootstrap.php</file>
</exclude>
</source>
Branch and path coverage
Add tests for the two red lines:
public function testExpressDoublesThePrice(): void
{
$this->assertSame(2000, $this->calc->cost(1200, 'PL', express: true));
}
public function testRejectsZeroWeight(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->calc->cost(0, 'PL');
}
Line coverage is now 100%. Run the same tests with Xdebug and --path-coverage (which includes branch coverage; --branch-coverage gives branches only):
$ XDEBUG_MODE=coverage php -d memory_limit=-1 vendor/bin/phpunit --coverage-text --path-coverage
...
Summary:
Classes: 50.00% (1/2)
Methods: 75.00% (3/4)
Paths: 50.00% (7/14)
Branches: 82.35% (14/17)
Lines: 100.00% (11/11)
App\Money
Methods: 100.00% ( 1/ 1) Paths: 100.00% ( 1/ 1) Branches: 100.00% ( 1/ 1) Lines: 100.00% ( 1/ 1)
App\ShippingCalculator
Methods: 66.66% ( 2/ 3) Paths: 46.15% ( 6/ 13) Branches: 81.25% ( 13/ 16) Lines: 100.00% ( 10/ 10)
Every line ran, yet 3 branches never did. They are all in isFree(). The only test passes 12000, so || short-circuits and ($member && $orderTotal >= 5000) is never evaluated. Line coverage hides this because the whole expression is on one line. The HTML report shows each branch and path with the tests that took it.
One more test covers the member rule:
public function testFreeForMembers(): void
{
$this->assertTrue($this->calc->isFree(6000, true));
$this->assertFalse($this->calc->isFree(6000, false));
$this->assertFalse($this->calc->isFree(4000, true));
}
Summary:
Classes: 100.00% (2/2)
Methods: 100.00% (4/4)
Paths: 64.28% (9/14)
Branches: 100.00% (17/17)
Lines: 100.00% (11/11)
Branches are at 100%, paths are not. cost() has 9 paths (the throw, plus 2 × 2 × 2 combinations of country, weight and express) and the tests run 4 of them. For example, no test sends a heavy express parcel abroad. 100% path coverage is rarely practical. Use the path report to find combinations that matter, such as two flags that interact.
Branch and path coverage with Xdebug are expensive. This tiny run needed 460 MB of memory and failed with PHP's default 128 MB memory_limit, which is why the command sets -d memory_limit=-1. With PCOV, --branch-coverage fails with No code coverage driver available that supports line and branch coverage.
Targeting: what a test is allowed to cover
#[CoversClass] says which code a test is meant to test. Code that a test runs but doesn't declare is not counted as covered by that test. That stops a high-level test from making code look tested when no test checks it directly.
Remove MoneyTest from the first example and run again: Money::format() still runs (through label()), but Money counts as 0% covered (the summary drops to 8/11 lines). ShippingCalculatorTest only declares #[UsesClass(Money::class)], which means "this code may run, but it isn't what I test".
The attributes, all in PHPUnit\Framework\Attributes (see Attributes):
| Attribute | Meaning |
|---|---|
#[CoversClass(Foo::class)] |
the test covers all methods of Foo |
#[CoversMethod(Foo::class, 'bar')] |
the test covers only Foo::bar() |
#[CoversFunction('slugify')] |
the test covers a global function |
#[CoversNamespace('App\Billing')] |
the test covers everything in a namespace |
#[CoversTrait(Foo::class)] |
the test covers a trait |
#[UsesClass(Foo::class)], #[UsesMethod], #[UsesFunction] |
code that may run but isn't counted |
#[CoversNothing] |
the test contributes no coverage at all (useful for smoke and integration tests) |
Two settings in phpunit.xml.dist enforce this:
<phpunit ...
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="true">
requireCoverageMetadata: a test without aCovers*orCoversNothingattribute is risky.beStrictAboutCoverageMetadata(same as--strict-coverage): a test that runs code it didn't declare withCovers*orUses*is risky.
Both checks only happen in runs that collect coverage.
With #[UsesClass] removed and the attribute missing from MoneyTest:
$ vendor/bin/phpunit --strict-coverage --coverage-text
...
R...R 5 / 5 (100%)
There were 2 risky tests:
1) App\Tests\MoneyTest::testFormat
This test does not define a code coverage target but is expected to do so
/home/kjk/shop/tests/MoneyTest.php:11
2) App\Tests\ShippingCalculatorTest::testLabel
This test executed code that is not listed as code to be covered or used:
- App\Money
/home/kjk/shop/tests/ShippingCalculatorTest.php:37
OK, but there were issues!
Tests: 5, Assertions: 5, Risky: 2.
...
Risky tests don't fail the run unless failOnRisky="true" is set. Targeting is a matter of taste. Strict targeting gives a precise "this class is tested by its own tests" number. Many applications skip it and count anything that ran. --disable-coverage-targeting ignores the attributes for one run, so you can compare the two numbers.
--covers 'App\ShippingCalculator' runs only the tests that declare they cover that class. This is a quick way to check one class's coverage.
Excluding code from coverage
Some code can't reasonably be tested: a fallback for a missing extension, a debugging helper. Mark it in the source with comments:
<?php
declare(strict_types=1);
namespace App;
final class Debug
{
/** @codeCoverageIgnore */
public static function dump(mixed $value): void
{
fwrite(STDERR, var_export($value, true) . PHP_EOL);
}
public static function memory(): string
{
if (!function_exists('memory_get_peak_usage')) {
// @codeCoverageIgnoreStart
return 'n/a';
// @codeCoverageIgnoreEnd
}
return round(memory_get_peak_usage() / 1048576, 1) . ' MB';
}
}
@codeCoverageIgnorein a docblock excludes the whole method, function or class.// @codeCoverageIgnoreat the end of a line excludes that line.// @codeCoverageIgnoreStart...// @codeCoverageIgnoreEndexcludes a block.
Ignored lines are removed from the totals, so they count neither as covered nor as missed. Use this rarely and for a reason. Every ignore makes the number less honest. --disable-coverage-ignore shows the real figure: for Debug it drops from 2/2 lines to 2/4.
The CRAP index
The HTML dashboard and --coverage-crap4j show the CRAP (Change Risk Anti-Patterns) index of each method. It combines cyclomatic complexity with coverage:
CRAP = complexity² × (1 − coverage)³ + complexity
A fully covered method scores its complexity. cost() above has complexity 5 and scores 5 at 100% coverage. The same method with no tests would score 5² + 5 = 30, PHPUnit's default threshold for a "crappy" method. Complex code with no tests is where bugs hide, so methods at the top of this list are the best places to add tests or to simplify.
Merging coverage from several runs
Unit tests, integration tests and tests on different PHP versions often run as separate jobs. Each job writes raw data with --coverage-php, and phpcov merges them:
composer require --dev phpunit/phpcov
vendor/bin/phpunit --testsuite unit --coverage-php build/cov/unit.cov
vendor/bin/phpunit --testsuite integration --coverage-php build/cov/integration.cov
vendor/bin/phpcov merge --clover build/clover.xml --html build/coverage --text php://stdout build/cov
phpcov 13.2.0 by Sebastian Bergmann.
Generating code coverage report in Clover XML format ... done
Generating code coverage report in HTML format ... done
Generating code coverage report in text format ...
Code Coverage Report:
2026-10-17 17:29:06
Summary:
Classes: 66.66% (2/3)
Methods: 80.00% (4/5)
Lines: 84.61% (11/13)
...
By default merge refuses to combine files made with different PHP versions, drivers or Git commits. The --do-not-require-matching-* options relax that. --source <dir> fixes paths when the .cov files were made on another machine.
Coverage of a change
phpcov patch-coverage checks only the lines a change added. This is useful as a pull request check in a legacy project where the overall number is low:
$ git diff master > change.patch
$ vendor/bin/phpunit --coverage-php build/coverage.cov
$ vendor/bin/phpcov patch-coverage --path-prefix "$PWD/" build/coverage.cov change.patch
phpcov 13.2.0 by Sebastian Bergmann.
1 / 2 changed executable lines covered ( 50.00%)
Changed executable lines that are not covered:
src/ShippingCalculator.php:21
$ echo $?
1
It exits with 1 when any added line isn't covered.
Coverage outside PHPUnit
php-code-coverage can be used on its own, for example to find out which code a CLI command or an end-to-end scenario runs. bin/cover.php runs another script under coverage:
<?php
declare(strict_types=1);
// Usage: php bin/cover.php <script.php> [args...]
require __DIR__ . '/../vendor/autoload.php';
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\Selector;
use SebastianBergmann\CodeCoverage\Filter;
use SebastianBergmann\CodeCoverage\Report\Facade;
$filter = new Filter();
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . '/../src'));
foreach ($files as $file) {
if ($file->getExtension() === 'php') {
$filter->includeFile($file->getRealPath());
}
}
$coverage = new CodeCoverage((new Selector())->forLineCoverage($filter), $filter);
$script = $argv[1];
$argv = array_slice($argv, 1); // the script sees its own name as $argv[0]
$coverage->start($script);
try {
require $script;
} finally {
$coverage->stop();
$report = Facade::fromObject($coverage);
$report->renderClover(__DIR__ . '/../build/script-clover.xml');
fwrite(STDERR, $report->renderText(null, showOnlySummary: true));
}
$ php bin/cover.php bin/quote.php 7500 DE
Shipping: 29.00
Code Coverage Report Summary:
Classes: 33.33% (1/3)
Methods: 40.00% (2/5)
Lines: 61.53% (8/13)
The report API (Report\Facade with renderHtml(), renderClover(), renderCobertura(), renderText() ...) has changed between major versions of php-code-coverage. Code from older tutorials that creates report classes such as Report\Html\Facade directly may not work with the current version.
At the lowest level, the drivers have their own functions. With PCOV:
<?php
// run with: php -d pcov.directory=. pcov-demo.php
\pcov\start();
require __DIR__ . '/grade.php';
echo grade(95), ' ', grade(70), PHP_EOL;
\pcov\stop();
$file = __DIR__ . '/grade.php';
$lines = \pcov\collect(\pcov\inclusive, [$file])[$file];
// 1 = executed, -1 = executable but not executed
foreach (file($file) as $i => $source) {
$mark = match ($lines[$i + 1] ?? null) {
1 => '+',
-1 => '-',
default => ' ',
};
printf("%s %2d %s", $mark, $i + 1, $source);
}
A pass
1 <?php
2 function grade(int $score): string
3 {
+ 4 if ($score >= 90) {
+ 5 return 'A';
6 }
+ 7 if ($score >= 50) {
+ 8 return 'pass';
9 }
- 10 return 'fail';
11 }
Xdebug's equivalents are xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE), xdebug_get_code_coverage() and xdebug_stop_code_coverage().
Pest
Pest runs on top of PHPUnit and uses the same drivers and <source> configuration. It has a built-in minimum check:
vendor/bin/pest --coverage --min=80
It prints a per-file table with the uncovered line ranges and exits with a non-zero code below the minimum. With PHPUnit, use a small script that reads the Clover file, as shown in Testing in CI.
Tips
- Use coverage to find untested code, not as a score to maximize. 100% line coverage with weak assertions proves little. A useful habit is to open the HTML report for the file you just changed and look at the red lines.
- Watch the trend. Fail CI when coverage drops below the current level, or check new code with
phpcov patch-coverage, rather than picking a big round number for an old code base. - Test the error paths. The red lines are usually
throw,catchand early returns for invalid input. Those are the paths that run in production at the worst moment (see Test exceptions). - Check branch coverage for code with complex conditions. Line coverage treats
a || (b && c)as a single line that either ran or didn't. - Keep coverage runs separate from fast runs. Even PCOV adds overhead. Run plain
phpunitwhile developing and collect coverage in one CI job. - Coverage only sees PHP that runs in the PHPUnit process. Code run in a subprocess (
#[RunInSeparateProcess]is handled by PHPUnit, butexec('php script.php')is not) or by a separate web server needs its own collection, for example with php-code-coverage as shown above. - Coverage shows that code ran, not that it was checked. To measure how good the assertions are, use mutation testing with Infection. It changes your code (flips
>=to>, removes a line) and reports changes that no test noticed.