Magento 2 – How to Run PHPUnit Commands from Any Location in CLI

clifilesystemintegration-testmagento2phpunit

In Magento 2 documentation "Running Unit Tests in the CLI" is text:

To run all tests, navigate to the Magento base directory and execute
the following command:

$ ./vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist

My question is: How can I run unit tests or integration tests without navigating to specific Magento directory?

So basically I would like to know the reason, why I have to be in specific directory to run phpunit commands in CLI? (I want to execute the command from any location)

EDITED:

Why I can not use full path to the vendor/bin/phpunit directory?

<path to Magento base directory>/vendor/bin/phpunit -c dev/tests/unit/phpunit.xml

ERROR THAT IT RETURNS:
Could not read "dev/tests/unit/phpunit.xml". Why the error appears?

Example: why I can not run /var/www/magento2/vendor/bin/phpunit -c dev/tests/unit/phpunit.xml when I am situated in /var/www/magento2/var/log $ location or anywhere else in the file system?

Reason: I want to create an app that allows me to speed up my development process. (I am not interested IDE-s) and I want to understand the reason why I have to navigate to the Magento base directory.

Best Answer

PHPUnit is installed by Composer, so it's executable is in the /vendor/bin directory. If you want to be able to run that program from anywhere in the command line, you need to add it to your path. Assuming you don't already have another version of phpunit installed globally, there are a couple of ways to do this:

  1. If you run export PATH=$PATH:/var/www/magento2/vendor/bin it will only last for the length of the session.

  2. You can permanently change it by adding that line to your ~/.bashrc file: export PATH=$PATH:/var/www/magento2/vendor/bin

  3. I think you can also create a symlink to phpunit to the /bin directory, but it's not best practice: https://unix.stackexchange.com/questions/116508/adding-to-path-vs-linking-from-bin

  4. Install phpunit globally another way (PEAR?), and don't use the version that M2 installs via Composer.

So now you can run Magento's phpunit anywhere. But you still need to pass the correct configuration to it.

Each test suite in Magento (unit, functional, etc) has a slightly different configuration, which is why you might pass it in via the -c dev/tests/unit/phpunit.xml.dist parameter, as you did in your example.

But if you rename phpunit.xml.dist to phpunit.xml, and if you run phpunit in the dev/tests/unit/ directory, it should automatically use the phpunit.xml file in that directory. This saves some typing.

What I would recommend is adding vendor/bin to your PATH, so you can run phpunit anywhere, then cd in to the test folder you want to run, rename the config files phpunit.xml, run your tests suites in those directories, for the shortest command.

You will still need to type out the full path to the actual tests you want to run, though.

Related Topic