Vuong
Posted on May 14, 2023
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
Enable xdebug if you're using it in Docker
docker-extension-enable xdebug
To check if Xdebug is already enable
php -i | grep xdebug
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
}
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
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/
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?
- PHPUnit configuration: https://docs.phpunit.de/en/9.5/code-coverage-analysis.html
- Add PHPUnit
@cover
tag in test class/functions.
- Add PHPUnit
This post are also related to XDebug https://dev.to/arielmejiadev/set-xdebug-coverage-mode-2d9g
Posted on May 14, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.