Unit testing in WordPress has come a long way with the help of WP-CLI, but it can still be a bit frustrating to set up correctly. These two tutorials were a great help to me when getting started:
But even with these great references I was having a rough time getting unit tests to run in my DesktopServer WordPress installations. What I didn’t realize is that you have to use the DS-CLI plugin in order to use the correct instances of MySQL, Apache, and PHP. One nice thing about DS-CLI is that it already comes bundled with WP-CLI, and PHPUnit, so you don’t have to handle the installation yourself.
So, here is how you set up your unit tests in DesktopServer:
- Open the DS-CLI and CD to your project’s plugin directory.
- Recommended: backup your database using the command
wp db export.
wp scaffold plugin-tests name-of-your-plugin-folder
- CD into your plugin’s root directory and run
bash bin/install-wp-tests.sh wordpress_test root '' localhost latest. Among other things, with this command we are creating a new database called “wordpress_test”. You can call the database whatever you like, just do not try to connect to your actual project database because it will be overwritten. This is why we made a database backup in step 2.
- Open up the /tests/bootstrap.php file in your plugin folder (this was created in step 3) and ensure the plugin file name on line 20 is correct. Change the file name if it’s not correct and save the file.
- CD to the plugin folder (still using DS-CLI) and run the command
- If all goes well you will see a success message for 1 test and 1 assertion.
Common sources of error are:
- Using the terminal rather than DS-CLI.
- The /test/bootstrap.php file is attempting to load a plugin file that does not exist.
- /tmp/wordpress-tests-lib does not exist. Fix: run
rm -rf /tmp/wordpress-tests-lib; bash bin/install-wp-tests.sh wordpress_test root '' localhost latestto remove relic files and reinstall the necessary WordPress test files.