Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Quality and Production

Testing WooCommerce Code

Test WooCommerce extensions with PHPUnit and WC helper factories, split unit from integration tests, fake gateways and HTTP, add Playwright E2E and a CI matrix.

A store extension changes prices, stock and orders. A bug there costs money, and "I clicked around and it seemed fine" does not scale past the third feature. Automated tests give you a safety net: you change code, run the suite, and learn within minutes whether you broke checkout.

This lesson explains the layers of testing for a WooCommerce plugin: fast unit tests for your own logic, integration tests that run inside a real WordPress with WooCommerce loaded, and a few end-to-end tests in a browser. The real test setups need WordPress and a database, so they are read-only here. The runnable examples show the most useful skill of all: designing code so that it can be tested, with fakes standing in for the outside world. For general WordPress testing, see Testing and Deployment.

The test pyramid for a plugin

flowchart TB
  E["E2E: a few browser flows<br/>Playwright, slow"] --> I["Integration: WordPress + WooCommerce<br/>PHPUnit, medium"]
  I --> U["Unit: your pure logic<br/>PHPUnit, very fast"]

Many fast unit tests at the base, fewer integration tests in the middle, a handful of browser tests on top.

  • Unit tests check one class or function with no WordPress, no database and no network. A price calculator, a slot capacity engine or a signature verifier are ideal. They run in milliseconds.
  • Integration tests load WordPress and WooCommerce, use a real test database, and check that your hooks, CRUD calls and settings work together with the platform.
  • End-to-end (E2E) tests drive a real browser through a real site: add to cart, check out, see the confirmation. They prove the whole chain works but are slow and fragile, so keep few of them.

The rule of thumb: put as much logic as possible in plain classes that depend on nothing, test those heavily, and use the slower layers for the glue.

Integration tests with the WooCommerce helpers

Integration tests extend WP_UnitTestCase (WordPress's PHPUnit base class). The database is reset between tests by wrapping each test in a transaction that is rolled back. WooCommerce's own repository has a test suite with helper classes that create realistic objects quickly, such as WC_Helper_Product, WC_Helper_Order and WC_Helper_Customer. Many extension authors copy or recreate a small version of these helpers, or build objects with the CRUD classes directly, because the helpers belong to WooCommerce's internal test code and can change. Check the version you target.

Here is the typical shape (read-only):

PHP
<?php
class Acme_Bulk_Discount_Test extends WP_UnitTestCase {

    public function test_ten_percent_off_from_five_items(): void {
        $product = new WC_Product_Simple();
        $product->set_name( 'Test notebook' );
        $product->set_regular_price( '20.00' );
        $product->save();

        WC()->cart->empty_cart();
        WC()->cart->add_to_cart( $product->get_id(), 5 );
        WC()->cart->calculate_totals();

        $this->assertSame( '90.00', wc_format_decimal( WC()->cart->get_total( 'edit' ), 2 ) );
    }

    public function test_no_discount_below_threshold(): void {
        // ... same setup with quantity 4, assert 80.00
    }
}

Practical advice:

  • Run tests in a throwaway environment such as wp-env (a Docker-based tool from the WordPress project) or the classic install-wp-tests.sh script with a separate test database. Never point tests at a real database.
  • Reset global state in set_up()/tear_down(): empty the cart, clear sessions, remove filters your test added. Static caches and the WC() singleton survive between tests.
  • Load WooCommerce first in your bootstrap file, then your plugin, so your hooks see a ready platform. Declare the paths with the constants your bootstrap defines.
  • Test behavior, not implementation: assert on totals, stock and statuses, not on which private method ran.

Make code testable: inject the outside world

The hardest things to test are anything that touches the outside: HTTP calls to a payment provider, the clock, random numbers, e-mail. The cure is dependency injection: pass those things in, behind a small interface, so a test can pass a fake.

PHP
<?php
interface Acme_Http {
    public function post( string $url, array $body ): array; // ['status' => int, 'body' => array]
}

class Acme_Gateway_Client {
    public function __construct( private Acme_Http $http, private string $apiKey ) {}
    // ... charge(), refund()
}

In production the implementation wraps wp_remote_post(). In tests you pass a fake that returns canned responses and records what was sent. Inside an integration test you can alternatively intercept WordPress HTTP with the pre_http_request filter, which lets a test return a response without any network call. Mocking a whole gateway means you test your own mapping from provider responses to order statuses, and you can simulate failures (timeouts, declines, duplicate events) that are hard to trigger for real. See Building a Payment Gateway.

PHP A mini test harness with a fake HTTP client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last test fails on purpose so you can see what a failing assertion reports. PHPUnit does the same job with much better output, data providers, and mocks; the idea is identical.

PHP Fakes for the clock and for stock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A test that depended on the real clock would have to wait 15 minutes or be flaky. A fake clock makes expiry a single line.

E2E tests with Playwright

For a few critical journeys, use a browser test tool. Playwright is the common choice in the WooCommerce world (the WooCommerce project itself uses it). A typical flow runs against a wp-env site seeded with known products and a known payment method:

JavaScript
import { test, expect } from '@playwright/test';

test('guest buys a notebook with the bank-transfer gateway', async ({ page }) => {
  await page.goto('/product/notebook/');
  await page.getByRole('button', { name: 'Add to cart' }).click();
  await page.goto('/checkout/');
  await page.getByLabel('Email address').fill('[email protected]');
  await page.getByLabel('First name').fill('Ada');
  await page.getByRole('button', { name: 'Place order' }).click();
  await expect(page.getByText('Order received')).toBeVisible();
});

Use stable selectors (roles and labels, not CSS classes), seed data through the REST API or WP-CLI rather than clicking through the admin, and keep the number small: login, add to cart, checkout with each gateway you ship, and one admin flow. Note that the cart and checkout can be the shortcode versions or the blocks versions, which have different markup; test the ones your customers use.

A CI matrix

Run the suite automatically on every push (GitHub Actions is typical). A matrix repeats the job over the combinations you support, so a break shows up before release:

  • PHP versions your plugin claims to support (for example 8.1, 8.3, 8.4).
  • WordPress: the minimum, the current release, and the nightly/trunk build.
  • WooCommerce: the minimum you declare, the latest stable and, if you can, the release candidate.
  • Optionally with HPOS on and off, since order storage differs (Orders and High-Performance Order Storage).

Add static checks alongside the tests: PHP_CodeSniffer with the WordPress and WooCommerce standards, and static analysis (PHPStan with the WordPress and WooCommerce stubs). Fail the build on any failure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do integration tests usually run in a throwaway environment such as wp-env?

    Integration tests create products and orders and reset the database. A separate disposable site and database keeps real data safe.
  2. 2. What is the main benefit of injecting an HTTP client into a gateway class?

    With the outside world behind an interface, tests can simulate declines, timeouts and duplicates without a network.
  3. 3. Which tests should you have the fewest of?

    Browser tests are slow and fragile, so keep a small set for critical journeys and push everything else down the pyramid.
  4. 4. What does a CI matrix add?

    A matrix runs the same suite over the combinations you promise to support, catching version-specific breakage early.

Summary

  • Test in layers: many fast unit tests, some integration tests inside WordPress and WooCommerce, a few Playwright journeys.
  • Integration tests use WP_UnitTestCase, a disposable site such as wp-env, and objects built with CRUD classes or helper factories; reset global state between tests.
  • Inject HTTP, time and storage behind small interfaces so tests can use fakes and simulate failures.
  • Keep E2E tests few, with stable selectors and seeded data.
  • Run everything in CI across a PHP, WordPress and WooCommerce version matrix, plus coding-standard and static-analysis checks.

Next: Performance and Scaling Large Stores