DEV Community

vuong ⛈️
vuong ⛈️

Posted on • Updated on

Code coverage for PHPUnit in VSCode

This post is listed points that I've worked to make code coverage works for my PHP. Mostly for reading again in my future but also able to share to everyone.

Install xdebug

https://xdebug.org/docs/install#pecl

pecl install xdebug
Enter fullscreen mode Exit fullscreen mode

Enable xdebug if you're using it in Docker

docker-extension-enable xdebug
Enter fullscreen mode Exit fullscreen mode

To check if Xdebug is already enable

php -i | grep xdebug
Enter fullscreen mode Exit fullscreen mode

Coverage Gutters extension

To show coverage gutters in VSCode for most of the programming languages, install this extension

Name: Coverage Gutters
Id: ryanluker.vscode-coverage-gutters
Description: Display test coverage generated by lcov or xml - works with many languages
Version: 2.10.4
Publisher: ryanluker
VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters

It helps to quickly run test with shortcut, you can have a preset of settings like every setting you could have CLI command or phpunit.xml.dist.

Extension's setting

{
    "coverage-gutters.showLineCoverage": true,
    "coverage-gutters.coverageBaseDir": "test-reports", // equivalent to ${workspaceFolder}/test-reports
}
Enter fullscreen mode Exit fullscreen mode

To run the unit tests and see the coverage

Run this command on terminal, your root project folder:

XDEBUG_MODE=coverage ./vendor/bin/phpunit --configuration phpunit.xml.dist --coverage-clover test-reports/cov.xml
Enter fullscreen mode Exit fullscreen mode

Then Toggle Coverage by Command Palette in VSCode

Dealing with PHPUnit mock types in VSCode

VSCode sometimes show error when writing Mock (but PHPStorm doesn't), this part can be solved by manual step:

It's really helpful to also install the Language Protocol Server for PHP https://intelephense.com/

https://github.com/sebastianbergmann/phpunit/blob/1f5e1334bb5de60471251a2392a9cc8d43bc4174/.phpstorm.meta.php

Copy this file to any child folder of the project, better to any git ignored folder. Then Intelephense can automatically solve the invalid type of VSCode. Which happened when you create mock from a class, and VSCode doesn't know how to detect it as original class or MockObject class, normally it will show as error if you don't do this step.

Why your code can't be cover?

This post are also related to XDebug https://dev.to/arielmejiadev/set-xdebug-coverage-mode-2d9g

https://xdebug.org/docs/all_settings#mode

Top comments (0)