Write unit tests for WordPress plugins with PHPUnit and WP-CLI scaffolding
WordPress unit tests run against a real WordPress loaded with a separate test database. Every test runs inside a database transaction that is rolled back afterwards, so each test starts from a clean state. WP-CLI generates the whole setup, and the base class WP_UnitTestCase gives factories for posts, users and terms, so the test data is one line.
Problem: A plugin has no tests: a change breaks existing behavior, and it is found only after deployment.
Solution: Scaffold the test suite with wp scaffold plugin-tests, install the WordPress test library with the generated script, write tests on WP_UnitTestCase with the factories, and replace external HTTP calls with the pre_http_request filter.
Set up
# In the WordPress folder: generates tests/, phpunit.xml.dist and bin/install-wp-tests.sh wp scaffold plugin-tests my-plugin cd wp-content/plugins/my-plugin # Downloads WordPress and the test library, creates the TEST database bash bin/install-wp-tests.sh wordpress_test root '' localhost latest # PHPUnit and the polyfills required by the WordPress test suite composer require --dev phpunit/phpunit:^9 yoast/phpunit-polyfills vendor/bin/phpunit
The first argument of the install script is the name of the test database. The test suite drops and recreates its tables on every run, so it must never be the database of a real site.
A function to test
<?php
// in the plugin: the discount of a customer, with an optional remote check
function myplugin_get_discount( $user_id ) {
$discount = (float) get_user_meta( $user_id, 'myplugin_discount', true );
$response = wp_remote_get( 'https://api.example.com/loyalty/' . $user_id );
if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
$data = json_decode( wp_remote_retrieve_body( $response ), true );
$discount += (float) ( $data['bonus'] ?? 0 );
}
return min( $discount, 50.0 );
}
The tests
<?php
// tests/test-discount.php
/**
* @group discount
*/
class Test_Discount extends WP_UnitTestCase {
private $user_id;
public function set_up() {
parent::set_up();
$this->user_id = self::factory()->user->create( array( 'role' => 'customer' ) );
// No real network calls in tests: answer every request with "no bonus"
add_filter( 'pre_http_request', array( $this, 'fake_api' ), 10, 3 );
}
public function fake_api( $preempt, $args, $url ) {
if ( false !== strpos( $url, 'api.example.com/loyalty/' ) ) {
return array(
'headers' => array(),
'body' => wp_json_encode( array( 'bonus' => $this->bonus ?? 0 ) ),
'response' => array( 'code' => 200, 'message' => 'OK' ),
'cookies' => array(),
);
}
return $preempt;
}
public function test_discount_from_user_meta() {
update_user_meta( $this->user_id, 'myplugin_discount', '10' );
$this->assertSame( 10.0, myplugin_get_discount( $this->user_id ) );
}
public function test_remote_bonus_is_added() {
update_user_meta( $this->user_id, 'myplugin_discount', '10' );
$this->bonus = 5;
$this->assertSame( 15.0, myplugin_get_discount( $this->user_id ) );
}
public function test_discount_is_capped() {
update_user_meta( $this->user_id, 'myplugin_discount', '80' );
$this->assertSame( 50.0, myplugin_get_discount( $this->user_id ) );
}
}
What happens here:
set_up()(with an underscore, the polyfills version ofsetUp()) runs before every test; the user created there disappears with the rollback after the test.self::factory()creates users, posts (->post->create()), terms and comments without managing IDs.pre_http_requestreturns a fake response beforewp_remote_get()touches the network, so the tests do not depend on an external service and run fast. Filters added in a test are removed automatically after it.@grouplets you run a part of the suite:vendor/bin/phpunit --group=discount.
NOTE: Test the behavior through public functions and hooks, not internal details: a test that checks that a filter changes the output (apply_filters( 'the_content', ... )) survives refactoring, while a test of private helpers breaks with every change. And run the suite on every push in CI, otherwise the tests are forgotten as soon as they become slow.