Running PHPUnit Tests in PhpStorm

Saturday, 18 November 2017

Test Driven Development (TDD) seems to be the phrase on every ones lips for sometime, but I have only recently gotten into doing TDD, and so far it is an enjoyable (albeit still slower) process. Having that confidence when you are making changes/refactoring, that everything still works, is a great feeling, especially when you spend most of your time working on projects with no tests, and having to manually test everything.

For TDD, I have been using PHPUnit, and at first, whilst becoming familiar with it, I was just switching to the terminal and running phpunit manually (for phpunit --filter TEST to run a specific test/file). Now whilst this is an easy way to go about it, it soon becomes quite tedious, switching from editor to terminal for every little change, but that is where your IDE can come in...

I use PhpStorm, and it has a built in way of running PHPUnit directly, so you don't have to ever leave the IDE to run your tests. I say ever, but I still run phpunit in the terminal, when I want to run the full test suite, but that is normally only when you have finished what you are doing, to make sure everything is still green, as well as the tests you have been running with your changes.

Once setup, you can run your unit tests in PhpStorm, with the following commands

Configuring PhpStorm

Now, this is all great, however, it does take a bit of setup, after a few times of trying to figure it out (seems it has to be done per project), I thought its time to get this noted down, so I don't have to figure it out every time.

So in PhpStorm, go to: Run > Edit Configurations... > Defaults > PHPUnit, and choose Defined in configuration file then select Use alternative configuration file, and then select your projects phpunit.xml file

PhpStorm edit configurations

If you try to run a test now, you will get this popup, with an Interpreter error at the bottom, click Fix to continue the setup.

PhpStorm interpreter Error

From here, select your Cli Interpreter, and click OK.

PhpStorm select cli interpreter

And the final setup, if you try to run a test, you will get this configuration error, click configure.

PhpStorm PHPUnit path error

Choose the Use Composer autoloader option, and set the path to your vendor/autoload.php file.

PhpStorm Set PHPUnit path

You are now good to go, and can run your PHPUnit tests within PhpStorm.

PhpStorm successful unit test

Happy testing!