Testing WordPress plugins: what I unit test, integration test, and skip

Most WordPress plugin test suites are either missing or slow, brittle and mocking WordPress itself. Here is how I split unit, integration and end-to-end tests so the suite catches real regressions and stays fast enough to run.

In short

  • The problem: a plugin update breaks checkout, settings or an integration on thousands of sites, and nobody noticed before release because the plugin has no tests, or has tests that only check that mocks were called.
  • What I do about it: I put business rules in plain PHP and unit test them hard, test everything that touches WordPress against a real WordPress and database, keep a handful of browser tests for the flows that make money, and deliberately skip the rest.
  • Who this is for: WordPress and WooCommerce plugin teams, agencies maintaining client plugins, and founders deciding how much testing to pay for.

A plugin release goes out on a Tuesday. By Wednesday the support queue has a pattern: saving settings on the "Advanced" tab silently resets the API key. The fix is one line. The damage is a day of support tickets, a hurried patch release and a few one-star reviews from people who had to reconnect their store.

When I look at plugins with this kind of history, the test suite is usually in one of two states. Either there isn't one, or there is a large one that mostly asserts that update_option was called with certain arguments. The second is worse in a way, because it gives the team confidence it hasn't earned. The mocked update_option happily accepted the wrong array, so the test passed and the bug shipped.

Testing a WordPress plugin well is less about tools and more about deciding what each kind of test is for. Here is the split I use.

Most bugs live at the WordPress boundary, so mocking WordPress hides them

WordPress plugins are glue code. They take a hook, read options or post meta, call a remote API, and write something back. The logic that is truly yours is often a small part of the file. The parts that break in production are usually where your code meets WordPress: a capability check that passes for the wrong role, a sanitize_* call that strips a value you needed, a meta query that behaves differently once HPOS (WooCommerce's newer order storage in custom tables) is enabled, a hook that fires twice.

A unit test that mocks every WordPress function can't see any of that. It tests your assumptions about WordPress, not WordPress. So my first rule is: don't fake the platform where the platform is the risk. Mocks belong at the edges you own and can describe precisely, not around get_option and WP_Query.

Unit tests are for business rules you pulled out of WordPress

The code that deserves fast, numerous unit tests is the code that would still make sense outside WordPress: price and tax calculations, proration, discount stacking, webhook payload parsing, state transitions for an order or subscription, mapping between your data and a remote API's format.

The trick is to make that code not depend on WordPress at all. If a class receives values and returns values, it needs no bootstrap, no database and no mocks. Plain PHPUnit runs hundreds of these in a second or two.

final class Refund_Calculator {
    /** Amounts in minor units (cents) to avoid float rounding. */
    public function refundable( int $paid, int $already_refunded, int $requested ): int {
        if ( $requested <= 0 ) {
            throw new InvalidArgumentException( 'Refund must be positive.' );
        }
        return min( $requested, max( 0, $paid - $already_refunded ) );
    }
}

final class Refund_Calculator_Test extends PHPUnit\Framework\TestCase {
    public function test_never_refunds_more_than_remaining_balance(): void {
        $calc = new Refund_Calculator();
        $this->assertSame( 300, $calc->refundable( 1000, 700, 500 ) );
    }

    public function test_fully_refunded_order_returns_zero(): void {
        $this->assertSame( 0, ( new Refund_Calculator() )->refundable( 1000, 1000, 100 ) );
    }
}

This is where testing pays back the design work. If a class constructs its own collaborators and reads globals, it can't be unit tested without heavy mocking. Passing dependencies in, as I described in dependency injection for WordPress plugins, is what makes this layer cheap.

When a pure class genuinely needs one or two WordPress helpers, such as __() for a message or apply_filters() for an extension point, I use Brain Monkey to stub those specific functions. If a unit test needs more than a few stubs, that is a signal: the code belongs in the integration layer, or it should be split.

Integration tests run against a real WordPress and a real database

Everything that reads or writes WordPress state gets tested against an actual WordPress install with a throwaway test database. That means REST routes, permission callbacks, settings save and sanitize paths, custom tables and migrations, post meta and order data, cron and Action Scheduler handlers, and the hooks you register.

The standard setup is the WordPress core test suite: WP_UnitTestCase, its object factories, and a database that each test resets. wp scaffold plugin-tests from WP-CLI generates the bootstrap, and @wordpress/env (wp-env) gives every developer and the CI runner the same Docker-based WordPress, so "works on my machine" stops being a debate. The core test library also depends on the Yoast PHPUnit Polyfills package, which you add through Composer.

A test I write on almost every plugin checks that the wrong user can't change settings through the REST API:

final class Settings_Route_Test extends WP_UnitTestCase {
    public function test_subscriber_cannot_update_settings(): void {
        wp_set_current_user( self::factory()->user->create( [ 'role' => 'subscriber' ] ) );

        $request = new WP_REST_Request( 'POST', '/acme/v1/settings' );
        $request->set_body_params( [ 'api_key' => 'attacker-value' ] );
        $response = rest_do_request( $request );

        $this->assertSame( 403, $response->get_status() );
        $this->assertNotSame( 'attacker-value', get_option( 'acme_settings' )['api_key'] ?? null );
    }
}

The second assertion matters as much as the first. A route can return the right status code and still have written the value before failing. Integration tests check what actually ended up in the database, which is what the customer experiences.

Other integration tests I consider non-negotiable:

  • Saving one settings tab doesn't wipe another. This is the bug from the opening, and it is common because settings are often stored as one serialized array.
  • Migrations run twice safely. Activation and upgrade routines get re-run more often than anyone expects.
  • Webhook and payment handlers are idempotent. The same event delivered twice must not create two orders or two refunds. I covered the pattern in idempotent WooCommerce payment webhooks.
  • Order code works with HPOS on and off, for any plugin that touches WooCommerce orders. Run the order tests in both modes in CI.
  • Uninstall removes what it should, and only that.

These tests are slower than unit tests, often a few seconds for a meaningful set, but they catch the bugs customers report.

End-to-end tests cover only the flows that make money

Browser tests click through the real admin and storefront. They are the only layer that catches a broken JavaScript bundle, a block that fails to render in the editor, or a checkout button hidden behind a CSS change. They are also the slowest and the flakiest, so I keep very few.

My rule: one end-to-end test per flow where a failure costs revenue or causes a support flood. For a commerce plugin that's usually adding to cart and completing checkout with a test gateway, the core settings screen saving correctly, and a block inserting and rendering in the editor. Five to fifteen tests, not two hundred.

I use Playwright with the @wordpress/e2e-test-utils-playwright package, which provides helpers like requestUtils for setting up state through the REST API instead of clicking through it:

import { test, expect } from '@wordpress/e2e-test-utils-playwright';

test( 'settings survive a save on another tab', async ( { admin, page, requestUtils } ) => {
    await requestUtils.activatePlugin( 'acme-shop' );
    await admin.visitAdminPage( 'admin.php', 'page=acme-settings&tab=advanced' );
    await page.getByRole( 'button', { name: 'Save changes' } ).click();
    await admin.visitAdminPage( 'admin.php', 'page=acme-settings&tab=general' );
    await expect( page.getByLabel( 'API key' ) ).not.toBeEmpty();
} );

Set up data through the API, assert through the UI. Tests that create every product by clicking are slow and break whenever a label changes.

What I deliberately skip

Choosing what not to test is part of the job. I skip:

  • WordPress and WooCommerce themselves. Don't test that register_post_type registers a post type. Test what your code does with it.
  • Thin wrappers with no decisions in them. A method that only calls get_option and returns the result doesn't need its own test; the integration tests that use it cover it.
  • Mock-call assertions as the main check. "Was wp_mail called once?" is fine as a supporting assertion. As the only assertion, it tests the implementation, not the behavior, and breaks on every refactor.
  • Pixel-level layout. Visual regression tools have their place on design-heavy products, but for most plugins they generate noise that teams learn to ignore.
  • Third-party APIs live in the main suite. Stripe or a shipping provider in every CI run means flaky builds and rate limits. Record or fake their responses at the HTTP layer, and keep a separate, occasional contract check against the sandbox.

Trade-offs and when not to do this

This split has costs, and it isn't right for every plugin.

The integration layer needs infrastructure. Docker, a database in CI and a working bootstrap take a day or two to set up properly on an existing plugin. For a 300-line plugin that adds one shortcode, that's out of proportion. A few integration tests run manually before release may be enough.

Extracting pure logic means refactoring. On a legacy plugin, business rules are tangled into hook callbacks. Pulling them out is worth it, but do it as you touch code, not as a three-month rewrite. Write an integration test around the old behavior first, then extract.

Coverage percentage can mislead. At SureCart I drove test coverage from 30% to 90% with PHPUnit and Jest, and the number was useful as a signal that testing had become a team habit. But a suite can hit 90% while missing the settings bug from the opening, because coverage counts executed lines, not checked outcomes. I treat coverage as a trend to watch, not a target to hit.

End-to-end suites rot fast without an owner. If nobody fixes flaky browser tests within a day, people start rerunning CI until it's green, and the suite stops meaning anything. Fewer tests that always pass are worth more than many that sometimes do.

Testing doesn't replace observing production. Some failures only happen with a specific host, cache layer or plugin combination. Tests reduce how often that happens; debugging in production safely covers the rest.

What I check on a project like this

  1. Can business rules run without WordPress? Pricing, refunds, payload parsing and state transitions live in plain classes with fast unit tests.
  2. Is there a reproducible test environment? wp-env or an equivalent, the same locally and in CI, set up with one command.
  3. Are permission and capability checks tested with the wrong user? Every REST route and admin action that writes data has a "denied" test that also checks the database.
  4. Do settings saves preserve unrelated values? Especially when options are stored as one serialized array.
  5. Are migrations and webhook handlers safe to run twice? Re-run activation and replay webhook events in tests.
  6. Does WooCommerce order code pass with HPOS on and off? Both modes in the CI matrix.
  7. Are there a few end-to-end tests on revenue flows, and does someone own them? Checkout, core settings, key blocks; flaky tests fixed within a day.
  8. Does CI block a release when tests fail? A suite that only runs when someone remembers doesn't protect customers.

The goal of a plugin test suite isn't coverage or tool choice. It's being able to ship an update to thousands of sites on a Tuesday without dreading Wednesday's support queue. Test your own rules fast and in isolation, test everything that touches WordPress against real WordPress, keep a short list of browser tests on the flows that make money, and be deliberate about what you leave out. That combination catches the bugs customers would otherwise find, and it stays fast enough that the team actually runs it.