What is Unit Testing?
Unit Testing is the process of writing code to ensure that other code functions with its expected behavior.
Why should I write tests?
Writing tests for your code can help drive the development of your code. This is referred to as Test Driven Development (TDD). Recently I was working on a method that sanitizes the input of a form field, and I needed this function to perform different conditionals and formatting. Instead of dumping a variable out and refreshing the page, to see the output, I was able to write test cases with what I expect the output to be, and the actual output that was returned. This allowed me to speed up the development process, and easily iterate through each condition I needed to sanitize against, and it ensured that the code returned what we wanted it to return.
Let’s Get Started
I utilize a custom Docker environment for my local development that has a separate container for PHP, MySQL, NGINX, and I’ve got a few others in there to help mimic my production environment but those aren’t really needed. I’m able to open up an SSH connection into the containers that have my site mounted, and I have access to WP-CLI. The only real requirement here is that you’ve got WP-CLI, but this walk through assumes you’re using something similar, you’ve got access to /tmp, and WP-CLI. Additionally you will need Composer, a PHP package manager, installed as that is how we’ll be requiring our vendor dependencies like PHPUnit.
If you’ve already got a plugin or theme setup but no tests, WP-CLI has the scaffold command which has a few options to scaffold just tests for a plugin or theme.
$ wp scaffold theme-tests <plugin-name> OR $ wp scaffold plugin-tests <theme-name>
The two above WP-CLI commands will scaffold all of the necessary files to begin writing tests, as well as providing a test-sample.php file.
This creates a phpunit.xml.dist file as well as the tests folder which contains the test-sample.php file.