Magento 2 and PHP Unit – ‘no tests executed’ issue

When starting on unit tests for a Magento 2 module, It seemed that phpunit refused to find any of my test methods. After some experimentation, I found a fix (well, maybe a workaround)

– copy (magento root)/dev/tests/phpunit.xml.dist to ./phpunit.xml, and then pass that as the config file (this was pretty obvious)
– you have to call Magento’s phpunit binary, not your system phpunit binary (this was way less obvious)

So where you could normally do something like

cd /path/to/magento2/app/code/YourCompany/YourModule/Tests/Unit ;
phpunit . ;

You instead need to do

cd /path/to/magento2/app/code/YourCompany/YourModule/Tests/Unit ;
./vendor/phpunit/phpunit/phpunit -c /path/to/magento2/dev/test/unit/phpunit.xml .

The problem with just doing ‘phpunit’ is it calls /usr/bin/phpunit, or whatever your local system phpunit is.

For convenience, you can replace the long file paths above with a couple symlinks and save yourself a LOT of typing. Become root on your system and do

cd /usr/bin ;
mv ./phpunit ./phpunit-system ;
ln -s /path/to/magento2/vendor/phpunit/phpunit/phpunit ./ ;
cd /path/to/magento2/app/code/YourCompany/YourModule/Tests/Unit ;
ln -s /path/to/magento2/dev/tests/unit/phpunit.xml ./ ;

You replaced the usual phpunti system binary with a symlink to Magento’s, and added a symlink to the phpunit config file in your modules unit tests directory. So now to run your module’s unit tests, just do

cd /path/to/magento2/app/code/YourCompany/YourModule/Tests/Unit ;
phpunit -c ./phpunit .