Testing Plugins

There are any number of ways to unit test WordPress plugins, but the right way would be the WordPress way. For that, we're talking a simple 3 step process:

Installing WP-CLI

WP-CLI provides a command line interface for WordPress. It's a simple PHP Phar file which can be downloaded and installed on most nix systems (with limited support for Windows). You can install it from terminal using the following commands. On Windows, you can perform all of these steps on WSL2-based nix systems without issue.

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

Install a local WordPress repository

WP-CLI requires an installed WordPress repository to perform the next step. When working on developing WordPress plugins and themes, it's always best to have as many WordPress versions as possible. For that purpose, it's best to use the WordPress Git repository.

git clone git@github.com:wordpress/wordpress

By using the above command to clone the WordPress Github repository, you will be able to run the bleeding edge version of WordPress locally, and test your plugins against any version of WordPress core.

Scaffolding your Plugin

Once WP-CLI and WordPress are installed, you will be able to use WP-CLI to scaffold your plugins. This scaffolding provides you with a base level for your plugins, including everything that you will need to get started with properly testing your plugins with phpunit. There are two main commands. The first is focused on scaffolding the entire plugin, while the second is focused on adding test scaffolding to existing plugins.

Scaffolding a Brand New Plugin

wp scaffold plugin <plugin name>

Scaffolding Plugin Tests to Existing Plugins

wp scaffold plugin-tests <plugin name>

Both of these commands must be run from inside a WordPress repository. You can see the full list of options for the scaffold command on the WP-CLI Docs.

Writing your tests

By default, with the scaffolding, tests are assumed to be unit tests. Test files are stored inside the plugin directory in <plugin root>/tests. Test files bust be written with the file name format test-<test name>.php.

WordPress tests are slightly different than regular PHPUnit tests, as the WordPress test class WP_UnitTestCase extends the PHPUnit class PHPUnit\Framework\TestCase.

What that does mean, though, is that all of the PHPUnit Test Case methods are available, but so are a few others:

Helper Methods

  • skipWithoutMultisite

  • skipWithMultisite

  • skipTestOnTimeout

  • expectDeprecated

WordPress Assertions

  • assertPostConditions

  • assertWPError

  • assertIXRError

  • assertNotIXRError

  • assertDiscardWhitespace

  • assertSameIgnoreEOL

  • assertEqualsIgnoreEOL

  • assertSameSets

  • assertEqualSets

  • assertSameSetsWithIndex

  • assertEqualSetsWithIndex

  • assertNonEmptyMultidimensionalArray

  • assertQueryTrue

Further Reading

Last updated