How to generate code coverage reports with PHPUnit?

by scotty_walker , in category: PHP General , a year ago

How to generate code coverage reports with PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@scotty_walker 

To generate code coverage reports with PHPUnit, follow these steps:

  1. Install PHPUnit: If PHPUnit is not already installed, you can install it using Composer by adding PHPUnit to your project's composer.json file and running composer update. Alternatively, you can install it globally by running composer global require phpunit/phpunit.
  2. Configure PHPUnit: Create a phpunit.xml or phpunit.xml.dist file in the root directory of your project. Define the necessary configuration settings, including specifying the source and test directories, coverage filter, and coverage report format. Here is an example configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    
        
            ./tests
        
    
    
    
        
            ./src
        
    
    
    
        
    


In this example, the source code resides in the ./src directory, the tests are located in the ./tests directory, and the coverage report will be generated in the ./coverage directory in HTML format.

  1. Run PHPUnit: Open your command line interface and navigate to the root directory of your project. Run the following command to execute your tests and generate the coverage report: For global installation: phpunit --coverage-html coverage For project-specific setup: vendor/bin/phpunit --coverage-html coverage Replace "coverage" with the desired output directory.
  2. Review the report: PHPUnit will generate a coverage report in the specified directory (in this case, ./coverage). Open the generated HTML files in your web browser to view the code coverage data. The report will show which lines are covered by tests and highlight any uncovered code.


Note: PHPUnit also provides coverage reports in other formats like Clover XML and PHP text format. You can modify the <logging> section in phpunit.xml to generate reports in different formats.