PHPUnit Command Line Code Coverage

I'm a big fan of unit testing, and for PHP projects I use PHPUnit. Combined with XDebug PHPUnit provides some great code coverage reporting options, including detailed HTML reports and a variety of different XML report options that work nicely with various different continuous integration servers and other tools.

A feature I've often wanted, that is currently missing from PHPUnit, is a simple command line display of code coverage statistics when you're running tests. If you're trying to improve the code coverage of a specific test it isn't practical to generate a full HTML report of the test every time you run it, and then check it in a browser. It would be much easier if the code coverage could be reported next to the success or failure message on the command line.

After a little bit of investigation into the different PHPUnit reports, and some git, awk, and sed hackery I came up with the following PHPUnit wrapper that does exactly what I was after. Once you've run a test, or collection of tests, it'll display a list of files affected by the test and the code coverage for each file. The code for this script is below:

# Call PHPUnit will all provided command line arguments, and also generate a metrics file
phpunit --log-metrics "$METRIC_FILE" $@
# If phpunit exits with an error then exit here with the same error code
if [ $? -ne 0 ]
   exit $?
# Do some manipulation of the metrics file and output each file and the coverage for that file
cat "$METRIC_FILE" | grep "<file" | awk '{print $2 $10}' | sed
"s|$PWD||g" | awk -F\" '{printf "%-50s %.2f%\n", $2, $4}'
# Cleanup

I've place the script in /usr/bin/phpuc on my machine, and then I can invoke it like so:

$ phpcs tests/ExampleTest.xml

PHPUnit 3.3.16 by Sebastian Bergmann.


Time: 0 seconds

OK (9 tests, 9 assertions)

Writing metrics report XML file, this may take a moment.
Example.php                     89.37%
IncludedFile.php                 12.9%

Hopefully this will be something that'll be built-in to PHPUnit in the future!

Posted on 14 Apr 2010
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.