Running PHPUnit Tests in Docker Container

Saturday, 28 April 2018

If like me, you are developing something across 2 machines, that have different setups, then Docker is a great way to ensure that your your application is running the same on both machines.

Now, you could also use vagrant, but for this project I decided on Docker, as we are looking to start using Docker at where I work.

Having my Docker files in my project, means that I know my application is working on the same server setup, regardless of the setup of my host machine. And this is important, cause my personal mac and work mac are setup with different versions of PHP. My personal mac has PHP 7 on it, however, my work mac still has PHP 5.5 on it, as that is what is required for what I work on there.

This brings complications for running PHPUnit directly on the machine, due to my work mac not having the correct version of PHP or PHPUnit on it, and this is where Docker comes in.

To get around the issue of not being able to run PHPUnit tests on my work mac, I looked into running my tests in the Docker container directly, and it is surprisingly easy to do.

One solution would be to install PHPUnit in your docker container, but that is not required.

Just use composer to install phpunit into your project (if you are using Laravel, this is already available for you).

composer require phpunit/phpunit --dev

From there you just need to run this command from your terminal, which will run your tests within your docker container.

docker-compose exec php php ./vendor/bin/phpunit

The first php is the name you have given your docker container, so docker-compose exec php is telling docker to run php ./vendor/bin/phpunit inside the container named php.

And that is it, you can now run your PHPUnit tests within your docker container.