Code Coverage VSCode With PHPUnit

May 24, 2024 note-to-self vscode

Need: Get some code coverage up for unit tests in vscode.

PHPUnit can handle outputting the necessary coverage information.

Coverage Gutters can read the outputting coverage file (in xml).

I'm running these in a docker container, so I wrote a bash script (bin/coverage) to make it easier.

#!/bin/bash

# These paths are from /var/www/html inside the container.
docker compose exec -u 0:0 <container_name> ./vendor/bin/phpunit -dxdebug.start_with_request=yes -dxdebug.mode=coverage --coverage-clover coverage/coverage.xml --testsuite Unit,Feature
docker compose exec <container_name> bash -c "/bin/sed 's+/var/www/html/++g' coverage/coverage.xml > coverage/updated && mv coverage/updated coverage/coverage.xml"
# note ^^^ sed -i doesn't work...

The reason for the sed shenanigans is that the paths were relative to the container, but I was editing outside the container. There is probably a more graceful way to do it, that I don't know about.

To run it:

> bin/coverage

To turn on the coverage in VSCode: How to open Coverage Gutters

VSCode Coverage Gutters unique to my settings.json:

    "coverage-gutters.coverageFileNames": [
      "lcov.info",
      "cov.xml",
      "coverage.xml",
      "jacoco.xml",
      "coverage.cobertura.xml"
    ],
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.