Unit Tests for your WordPress plugin using WP CLI and PHPUnit

Often when I write a blog post, part of the reason I write it is to document things that I tend to forget. This is one of those times.

Requirements:

PHPUnit: At the time of this writing, WordPress only supports the latest stable 7.x version of PHPUnit, and recommends installing it globally.

wget https://phar.phpunit.de/phpunit-7.5.9.phar
chmod +x phpunit-7.5.phar
sudo mv phpunit-7.5.phar /usr/local/bin/phpunit
phpunit --version

WP-CLI: If you’re developing on WordPress and you’re not using WP-CLI, you are missing out on some amazing tools.

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar 
sudo mv wp-cli.phar /usr/local/bin/wp

Set up

Using WP-CLI, you can quickly scaffold some unit tests files for your WordPress plugin.

Inside the WordPress directory of the site you’re building/testing on, run the following command to scaffold the unit test code for your plugin, located at /wp-content/plugins/plugin-name

wp scaffold plugin-tests plugin-name

If you don’t already have a plugin directory, because you’re building the plugin from scratch, you can just run the following command to scaffold some initial plugin code, which includes the unit test code.

wp scaffold plugin-name

Either way, you’ll end up with a ‘tests’ directory inside your plugin directory, which includes the test bootstrap file, and a sample test file.

The next step is to set up the ‘wordpress_test’ database, which the test suite will use when creating mock posts etc. Switch to the plugin directory and run the following comand, replacing ‘root’ and ‘password’ with your local MySQL servers username and password.

bash bin/install-wp-tests.sh wordpress_test root password localhost latest

And you’re done, go forth and write some unit tests for your WordPress plugin.

WordPress.com

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.