Continuous Testing with PHPUnit

Lately I have been doing a lot of TDD (Test Driven Development), which has been refreshing. I can tell that it has been taking me a bit longer to get things done but I can also tell that the quality of my code is better. Better still, when I do a refactoring cycle I spend less time manually testing my changes and tracking down weird little issues that I have introduced.

One thing that I have been doing that has greatly increased the speed of my development is to continuously run my tests in the background while I am making changes. Since the tests run so quickly I can immediately get feedback when there is a new issue. One simple way of doing this is to use a “watch” command.

watch -c "phpunit"

With my windows arranged in such a way that I can see the tests off to the side while my code takes up most of the screen I can quickly see things as they come up and react before I get too far along, introducing more compounding issues.

Running all of the tests might be a bit too much in some cases however. I find that if I am working on new code that doesn’t yet touch anything else, or rather nothing else is depending on, I can limit the tests to just those that I am actively writing.

watch -c "phpunit --filter 'MyNamespace\\\\SpecificTest'"

Note the double escaped backslash, escaped once for the inner single quotes and once for the outer double quotes.

On the other hand when I am working on refactoring some existing code I like to run any tests that might break as a result of my changes. You could run the full test suite as in the first example, which is probably fine if your code base is not too big. But if you have a very large code base with a quickly growing number of tests you might not want to run all of them every few seconds. What I have started doing to get around this issue is to break the tests up into logical groups and then “watch” a group while I work.

watch -c "phpunit --group myGroup"

This is accomplished by using the @group PHPUnit annotation of which you can have as many as you like.

screenshot

For more information about PHPUnit checkout the extensive documentation at phpunit.de. Look into the “The Command-Line Test Runner” section for details on the command line options that are available such as --filter and --group.

The watch command that I use is available in most Unix environments but I got it through homebrew since there isn’t one built into macOS (brew install watch). The -c flag ensures that ANSI color and style sequences are interpreted, so that you get the nice colors for failing and skipped tests etc.