Run test command with composer

For PHPUnit test, you might have different version for your local dependency and global installation.

You might have installed latest version of composer globally and older version of composer for you local project like me.

For globally you can run phpunit command from your terminal.

But for the local project with different dependency you can not run phpunit from terminal for test. Because your local project might not compatible with the latest version of PHPUnit . Same things happen for me.

I install 9.5.0 as global and 7.5.9 for local WordPress project dependency. So I can not run phpunit from my local project. It gives error like below.

C:\xampp\htdocs\wpunittest\wp-content\plugins\myplugin  (myplugin@0.1.0)
λ phpunit
PHP Warning:  Class 'PHPUnit\Util\Getopt' not found in C:\Users\thean\AppData\Local\Temp\wordpress-tests-lib\includes\phpunit6\compat.php on line 17

Warning: Class 'PHPUnit\Util\Getopt' not found in C:\Users\thean\AppData\Local\Temp\wordpress-tests-lib\includes\phpunit6\compat.php on line 17
Error: Looks like you're using PHPUnit 9.5.10. WordPress requires at least PHPUnit 5.4 and is currently only compatible with PHPUnit up to 7.x.
Please use the latest PHPUnit version from the 7.x branch.

It actually shows that, PHPUnit version is not compatible with your local dependency.

So you need install compatible version of PHPUnit for your local depency, like below.

composer require --dev phpunit/phpunit 7.5.9

Now you can run PHPUnit test command from your local project. like below.

./vendor/bin/phpunit

It will give you message like below.

But you can run your command with composer. You need to add a simple script in your composer.json file. Here is the script.

"scripts": {
    "test": "@php ./vendor/bin/phpunit"
}

Now you can run your test command with composer.

composer run test

It will give you the same result like above.

Now you write your test for your project and run it from composer.