Recently we finished a green field project written in php with laravel as a framework, that was carried out under the Test Driven Development methodology right from the start.
Test Driven Development is the preferred way for building high quality and scalable software. The biggest benefit is the ability to change the requirements and implementation and having a short feedback loop, of that if something went wrong.
We decided to check its code coverage at the end, to have some idea about the amount of tests we have and how much of the code they cover.
After some research, it turned out, that it is pretty simple.
You just need to have xdebug enabled and it will do all the heavy lifting.
Enabling xdebug for testing
If you are not sure, if you have xdebug enabled follow this paragraph, else you can proceed with the phpunit.xml update.
Run php –ini to find your xdebug configuration file. Mine is located in /usr/local/etc/php/7.0/conf.d/ext-xdebug.ini
It should look like following snippet, if it is working.
zend_extension="/usr/local/opt/php70-xdebug/xdebug.so" xdebug.remote_enable = 1 xdebug.remote_autostart = 1
After turning on xdebug, you don’t need to restart anything as we will be running the tests from the console.
Since xdebug will do all the work, just add the following lines to your phpunit.xml file. I’ve added them bellow the listeners tag.
<logging> <log type=”coverage-clover” target=”tests/_reports/logs/clover.xml”/> <log type=”coverage-html” target=”tests/_reports/coverage” charset=”UTF-8″ yui=”true” highlight=”true” lowUpperBound=”35″ highLowerBound=”70″ /> <log type=”testdox-text” target=”tests/_reports/testdox/executed.txt”/> </logging>
You might comment this section in development mode and use it only when you want to generate new report.
Preparing the code coverage report
To prepare the report just run phpunit in you project and wait for it to finish the execution.
You should be patient, because it was more than 6 times slower for my project, than normal run of the tests with xdebug enabled.
Finally the results should appear in tests/_reports/coverage, where you will find index.html file, which you can use to start browsing your test coverage report.
Tips on tests speed
– If you are not a debugger just disable xdebug and your test suite will run so much faster (in my case around 4 times faster).
– If you are using laravel and its authentication system during tests, decrease the encryption algorithm complexity only for you tests, by adding the following line to your createApplication method located in tests\CreatesApplication trait, to make them run even faster (2x performance boost for me).
– You might use johnkary/phpunit-speedtrap to report you which tests are running slow, so you can try to improove them.
– Finally this one is not speed related, but I really like it codedungeon/phpunit-result-printer. You might install this package to change the way executed tests are presented in the console.