lundi 4 octobre 2021

Configure XDebug for code coverage in PhpStorm


A frequent problem when running TDD or legacy testing workshops is to get code coverage for PHP to work within PhpStorm. In fact XDebug is needed and it can be a bit tricky to install on some configurations. This post shows how to make it work any time, by running it within a docker container.

PhpStorm has the ability to run the php executable, for testing or for debugging using a docker container. While that's easy and well documented we also need a docker image with xdebug installed and we also need to configure the code coverage to NOT try to code cover the whole "vendor" directory which would be slow to say the least. So let's dive into how it's done

Configure a php cli to run in docker

Open settings and click on the "three dots"






Click "+"





Choose "From docker, Vagrant, ..."




Enter the full image name. 





At this stage your tests should run, the debugger should work. You might have to configure the "Test Framework" in the settings, and in particular the autoloader to use. For instance 





Note for PHP > 7.3 : PhpStorm produced images up until PHP7.3. But if you need 7.4 or above you'll have to make your own. For instance here's the whole Dockerfile you need for 7.4

FROM php:7.4
RUN pecl install xdebug-3.1.0
RUN docker-php-ext-enable xdebug

Configure the code coverage to exclude vendor

It boils down to use the option of "whitelist" or the more recent "coverage" to tell phpunit which source code to instrument for code coverage.

While it should work to pass options to phpunit to ignore vendor, it seems that PhpStorm makes this impossible. I've never been able to configure this without an xml file. On the other hand with the xml file it's easy.




 



Add a section "filter" or "coverage" with your source code directory.












Now you're ready to run the tests with code coverage




Aucun commentaire:

Enregistrer un commentaire