I want to write unit tests for a plugin. I have used WP-CLI to scaffold the test WordPress instance and can successfully run tests.
The plugin I’m writing unit tests for is a site specific plugin rather than a stand-alone plugin destined for the wordpress.org repository. Being a site specific plugin, some functions use functions provided by other plugins, Advanced Custom Fields for example.
Question: How do I install and load additional plugins, within the WP-CLI scaffolded site, when testing my site specific plugin?
I looked at the bin/install-wp-test.sh
file hoping I could add additional wp-cli commands to install and activate the required plugins, but this script does not appear to use wp-cli to create the test WordPress instance.
I’ve also tried updating the _manually_load_plugin
functions within tests/bootstrap.php
file with the following code, but it had no effect.
/**
* PHPUnit bootstrap file
*
* @package Site Specific Plugin
*/
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir="/tmp/wordpress-tests-lib";
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Manually load the plugin being tested.
*/
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/battingforchange.php';
// Update array with plugins to include ...
$plugins_to_active = array(
'advanced-custom-fields-pro/acf.php'
);
update_option( 'active_plugins', $plugins_to_active );
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
2 Answers
What you are trying to do is not unit testing but integration testing, and as integration usually requires some initialization which will be specific to the relevant plugin it is hard to give a general answer which is more then the obvious”include the plugin file”
The idea of unit testing is to check that your APIs do what they are supposed to do and the base assumption should be that external APIs work correctly, otherwise there is just no limit to the amount of tests you will have to write.
Once you assume that the external APIs work correctly it doesn’t make any difference if you actually call them or just write a function in the same name that just mimics their behavior.
As an example to the idea. In a plugin I write there are several settings that control with which argument WP_Query
is being called. To test that I just check the resulting array of argument without bothering actually calling WP_Query
.