PHPUnit testing WordPress Plugin

Using answers on this site and from other resources, I have started writing my next plugin using PHPUnit tests and the WordPress test environment. Distilling down what I have in my plugin’s bootstrap.php:

define( 'WP_TESTS_DIR', 'pathToMyWordPressTestsFromSVN');
define( 'TEST_PLUGIN_FILE', 'pathToMyPlugin/myPlugin.php' );
require_once WP_TESTS_DIR . 'includes/functions.php';
require WP_TESTS_DIR . 'includes/bootstrap.php';

function _manually_load_plugin() {
    require TEST_PLUGIN_FILE;
    if(is_plugin_active(TEST_PLUGIN_FILE)){
        echo "PLUGIN IS LOADED AND WORKING!!!!";
    }
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );

// Normally you'd find "require WP_TESTS_DIR . 'includes/bootstrap.php';" down here...

In essentially every example, the WordPress test environment bootstrap.php is loaded last.

This seems strange because if I load it earlier, I get access to functions like is_plugin_active which I imagine will be useful when testing plugins that require others…and bailing out if the requirements aren’t loaded for some reason.

Is there a reason the test environment is bootstrapped at the end…other than habit/convention?

1
1

The reason the WordPress test bootstrap is loaded at the end is precisely because it loads WordPress:

// Load WordPress
require_once ABSPATH . '/wp-settings.php';

If you don’t hook your function to load your plugin to 'muplugins_loaded' before including the bootstrap, your plugin won’t be loaded with WordPress. In most cases that will mean that your plugin won’t get set up properly (e.g., 'init' will have already been fired before your plugin’s functions get hooked up).

As far as checking for dependencies, you could probably do that by hooking into the 'plugins_loaded' action:

function _check_for_dependencies() {
    if ( ! is_plugin_active( 'some-plugin/some-plugin.php' ) ) {
        exit( 'Some Plugin must be active to run the tests.' . PHP_EOL );
    }
}
tests_add_filter( 'plugins_loaded', '_check_for_dependencies' );

Or, you can just let WordPress’ bootstrap load completely and check for your dependencies after it.

Leave a Comment