Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to create code coverage reports in text and HTML formats. The more code is covered the better.


Prerequisite


Make sure XDebug is enabled in your server. Use $ sudo apt-get install php-xdebug command to install it.


$ php -v
PHP 7.0.22-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.22-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies
with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

Text version


This will create report.txt file under tests/coverage folder.


$ vendor/bin/phpunit --coverage-text=tests/coverage/report.txt

# tests/coverage/report.txt

Code Coverage Report:
2017-10-22 20:16:39

Summary:
Classes: 83.33% (5/6)
Methods: 91.67% (11/12)
Lines: 96.97% (32/33)

\Application\Exception::PostcodesException
Methods: 100.00% ( 1/ 1) Lines: 100.00% ( 2/ 2)
\Application\Service::PostcodeService
Methods: 100.00% ( 2/ 2) Lines: 100.00% ( 3/ 3)
\Application\Service::TwitterService
Methods: 100.00% ( 2/ 2) Lines: 100.00% ( 3/ 3)
\Application\Service::UserService
Methods: 100.00% ( 2/ 2) Lines: 100.00% ( 5/ 5)
\Application\Util::ParameterUtil
Methods: 100.00% ( 2/ 2) Lines: 100.00% ( 8/ 8)
\Application\Util::Postcodes
Methods: 66.67% ( 2/ 3) Lines: 91.67% ( 11/ 12)

Terminal version


This will print coloured version of what you see above in terminal. You need to add code below to your phpunit.xml.dist file. However, if you don't want to change the phpunit.xml.dist the just use vendor/bin/phpunit --coverage-text instead.


<logging>
<log lowUpperBound="35" highLowerBound="70" showUncoveredFiles="true" />
<log type="coverage-text" target="php://stdout" showUncoveredFiles="true"/>
</logging>

$ vendor/bin/phpunit


HTML version


This will create relevant files under tests/coverage folder.


$ vendor/bin/phpunit --coverage-html tests/coverage


Alternatively you can add code below to phpunit.xml.dist file and run vendor/bin/phpunit command.


<logging>
<log type="coverage-html" target="tests/coverage" lowUpperBound="35" highLowerBound="70" />
</logging>