Testing in Docker

A quick video on running PHP unit tests against different versions of PHP using Docker.

We cover unit testing with PHP.

Our Goals:

  1. Unit test to version of PHP you want
  2. Watch for file changes

Without Docker:

We can use a utility called pywatch to run a command when files are changed. Here's how we create a new Laravel project and run unit tests automatically when they're updated:

cd ~/Sites
composer create project laravel/laravel docker-testing

cd docker-testing

virtualenv .venv
source .venv/bin/activate
pip install pywatch

pywatch ./vendor/bin/phpunit ./tests/*.php

This works pretty great, but what if we want to test a specific version of PHP when we run our unit tests? Docker can help us there.

With Docker

docker pull php:7.0-cli
# See the new docker images we pulled down
docker images

# Run PHP in a container to run our local phpunit
docker run --rm -v ~/Sites/homestead/docker-testing:/opt php:7.0-cli php /opt/vendor/bin/phpunit /opt/tests

That's good, but let's use pywatch in a container to run unit tests automatically. We'll make our own Docker image. Create a new file named Dockerfile

FROM php:7.0-cli


RUN apt-get update
RUN apt-get install -y python-pip
RUN pip install -U pip
RUN pip install pywatch


ENTRYPOINT ["pywatch"]

Then we can build our Docker image and try it out:

mkdir docker
cd docker

# create Dockerfile here

# Create a new Docker image named "phptest" and tag it as PHP 7.0
docker build . -t phptest:7.0

# Try running the new image
docker run --rm -it -v ~/Sites/homestead/docker-testing:/opt phptest "php ./vendor/bin/phpunit" ./tests/*.php

This uses the pywatch command set as the ENTRYPOINT and appends the other commands we added. The full command run in the container becomes pywatch "php ./vendor/bin/phpunit" ./tests/*.php, which watches the files in the tests directory ending in .php.


Sign up to get announcements as well as
over 20 free videos on Docker in Development,
a course preview on Dockerizing Your Applications, and more!

What to learn more? Read the blog.


the true grumpy programmer, don't be fooled by imitation

I'm Chris Fidao. I wrote the Servers for Hackers eBook, and publish related videos at the Servers for Hackers video site. I also curate the Servers for Hackers newsletter, which is read by over 12,000 programmers who want to learn about servers.

I'm also the author of the Deploy PHP! video series, a video series about automating your deployments. A few years ago, I wrote Implementing Laravel, a book all about coding in Laravel - now offered free!