Unit Testing : from PhpUnit to Coverage Report

July 22, 2020
php phpunit testing

If you want to be confident each time you add a new functionality in your code, or when you need to change some old code of your application unit tests are a necessity. In this article, I will not try to convince the few (I hope) developers reticent with unit testing but rather showing you how to implement it without hustles.

1. Installing our tools

On a Symfony project simply run composer require — dev symfony/phpunit-bridge

2. Running our tests


Add a phpunit.xml file at the root of your project :

<phpunit colors="true">
        <testsuite name="Manager Test Suite">

In order to get color highlight in our terminal we can configure our phpunit.xml with thecolors="true"option.

Get the results

result colored

Result of our tests

3. Code Coverage

Now that we test our codebase and see which tests are failing, we can go further. Once all our tests are green we need to know what we should test next. Or which tests are too weak.


Add a phpunit.coverage.xml file at the root of your project :

<phpunit colors="true">
        <testsuite name="Manager test suites">
        <log type="coverage-html"
<!--        files with at least one line executed appears in report-->
        <whitelist addUncoveredFilesFromWhitelist="false">
            <directory suffix=".php">./Manager</directory>

You can now change phpunit options as you want :


Run this to see the generated coverage report : /.bin/phpunit -c phpunit.coverage.xml

Using the previous configuration, this command will run our tests again but thanks to Xdebug it will generate an html report.

code report

The html coverage report can now be found at the target location configured in our phpunit.coverage.xml , in our case : .log/codeCoverage

comments powered by Disqus