A Pollora project is tested with Pest, which runs on PHPUnit, through composer test. Plain classes take an ordinary unit test; code that needs WordPress takes a feature test that loads the site first; and the asynchronous actions, the scheduler and the options have helpers so a test does not queue, schedule or store anything for real.
- The runner and
composer test - What the test environment changes
- A first unit test
- A first feature test that reaches WordPress
- Fakes and helpers
- In a CI job
Since v13.43.0 the skeleton requires pestphp/pest in require-dev, next to phpunit/phpunit, Mockery and Faker. Its own tests are written in Pest (it(), expect()), and tests/Pest.php binds Tests\TestCase to every test under tests/Feature, so a Pest feature test boots the application and WordPress without extending anything. Test classes written for PHPUnit (extends TestCase, test_* methods) still run under php artisan test. Process isolation does not work under Pest: see Why it runs in its own process.
composer test clears the configuration cache, then runs Laravel's test command:
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
]phpunit.xml defines two suites, Unit (tests/Unit) and Feature (tests/Feature), so you can run one of them, or one file, through the same command:
composer test
php artisan test --testsuite=Unit
php artisan test tests/Feature/FrontPageTest.php
php artisan test --filter=FrontPageTestA fresh skeleton ships tests of its own. tests/Unit checks that the WordPress core patch and the Composer patches are in place. tests/Feature/Installation checks the installation: the .env file, the database connection, the WordPress tables and options, and, over HTTP, that APP_URL answers. Those need an installed site and a web server serving APP_URL.
Two other scripts exist for the skeleton's own maintenance: composer test:integration (a suite of HTTP checks against a running site, whose URL comes from POLLORA_TEST_URL) and composer test:install. They are not part of composer test.
phpunit.xml sets, for the run:
| Setting | Value |
|---|---|
APP_ENV |
testing |
CACHE_STORE |
array |
QUEUE_CONNECTION |
sync |
SESSION_DRIVER |
array |
MAIL_MAILER |
array |
Pollora maps the testing environment to WordPress's development environment type, so wp_get_environment_type() returns development during a test, and DISABLE_WP_CRON is on.
Two things to know:
- PHPUnit's
<env>does not replace a variable that is already set. If your shell exportsAPP_ENV=local, the tests run aslocal. phpunit.xmldoes not choose a database: itsDB_CONNECTIONandDB_DATABASElines are commented out. The tests use the database of your.env, which is the one holding your WordPress site. Point.envat a separate database for the tests, or use a throwaway one in CI, before a test writes anything.
A class that does not call WordPress or Laravel needs no base class. The skeleton's tests/Unit/ExampleTest.php is a Pest test of this kind:
// app/Support/Vat.php
namespace App\Support;
final class Vat
{
public static function including(int $cents, float $rate): int
{
return (int) round($cents * (1 + $rate));
}
}// tests/Unit/VatTest.php
use App\Support\Vat;
it('adds the rate', function (): void {
expect(Vat::including(1000, 0.2))->toBe(1200);
});The same test as a PHPUnit class (class VatTest extends PHPUnit\Framework\TestCase with a test_it_adds_the_rate() method and $this->assertSame()) runs just as well.
When the class takes the options repository, mock OptionRepositoryInterface rather than WordPress: see Options, Unit Testing.
Tests\TestCase extends Laravel's TestCase, so a feature test boots the application, and Pollora loads WordPress with it. What it does not do is process a request. A test that asks WordPress what it would do for a URL (which page is it, is it a 404) has to set the URL and ask WordPress to parse it.
A feature test that only needs WordPress loaded (a function, a registered post type, the options) needs nothing more:
// tests/Feature/EventPostTypeTest.php
it('registers the event post type', function (): void {
expect(post_type_exists('event'))->toBeTrue();
});To ask WordPress about a URL, add a base class once:
// tests/WordPressTestCase.php
namespace Tests;
abstract class WordPressTestCase extends TestCase
{
protected string $uri = '/';
protected function setUp(): void
{
$_SERVER['REQUEST_URI'] = $this->uri;
$_SERVER['SERVER_NAME'] ??= 'localhost';
$_SERVER['HTTP_HOST'] ??= 'localhost';
defined('WP_USE_THEMES') || define('WP_USE_THEMES', true);
parent::setUp();
wp();
}
}Then a test declares the URL it visits and runs in its own process. This is a PHPUnit class, and the process attributes are a PHPUnit feature: put it in a directory that no suite of phpunit.xml lists (here tests/Isolated, so that php artisan test does not pick it up) and run it with PHPUnit's own runner, vendor/bin/phpunit tests/Isolated. Run by php artisan test (that is, by Pest), it fails with Class "PHPUnit\TextUI\Configuration\Registry" not found:
// tests/Isolated/UnknownUrlTest.php
namespace Tests\Isolated;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use Tests\WordPressTestCase;
#[RunTestsInSeparateProcesses]
#[PreserveGlobalState(false)]
final class UnknownUrlTest extends WordPressTestCase
{
protected string $uri = '/no-such-page/';
public function test_an_unknown_url_is_a_404(): void
{
$this->assertTrue(is_404());
}
}With protected string $uri = '/' (the default), is_front_page() is true. WordPress's conditional tags (is_page(), is_singular(), is_post_type_archive()…) answer for the URL, and get_queried_object() returns what WordPress found. The site must be installed (php artisan pollora:install) and the database must be reachable.
Under php artisan test the application runs in the console. In a console run, the framework does not switch the theme layer on: it defines WP_USE_THEMES as false (src/WordPress/Bootstrap.php in pollora/framework, defineWordPressConstants()). Nothing parses the URL either. In a test without the base class above, WP_USE_THEMES was false and both is_front_page() and is_404() returned false whatever the URL, because WordPress had not run its query.
The base class does what a web request does. It sets REQUEST_URI and the server variables, defines WP_USE_THEMES as true if nothing has defined it yet, before the application boots, and calls wp(), the WordPress function that parses the request and builds the main query.
WP_USE_THEMES is a PHP constant, and a constant is defined once per process. The first test to define it, or to let the framework define it, decides the value for every test after it. The same goes for the other WordPress constants and globals and the files WordPress has loaded. #[RunTestsInSeparateProcesses] starts a new PHP process for each test of the class, with #[PreserveGlobalState(false)] so the child does not inherit the parent's globals. The framework's own test of the WordPress constants, tests/Unit/WordPress/BootstrapEnvironmentTest.php, uses these two attributes for the same reason.
Three details:
- Put the attributes on the test class itself. Placed on an abstract base class, they were not applied: the tests of a class extending it shared one process.
- Instead of attributes,
vendor/bin/phpunit --process-isolationruns every test in its own process. It is slower. - Pest has no process isolation.
php artisan test --process-isolationandvendor/bin/pest --process-isolationstop withThe [--process-isolation] option is not supported,->runInSeparateProcess()is an undefined method on a Pest test, and withprocessIsolation="true"inphpunit.xmlthe tests fail with a PHP parse error in the child process.
WordPress includes a theme's functions.php and a plugin's main file once per process, while a test process builds one application per test. From Pollora 13.45.2, the pollora_register() calls made while WordPress loads are repeated for each later application, so the views, the configuration and the providers of the theme and of those plugins are there in every test. What they hook into plugins_loaded, setup_theme, after_setup_theme, widgets_init, init and wp_loaded runs again, and the callbacks of the earlier application they replace are unhooked. This needs no configuration and happens only when APP_ENV is testing.
Only pollora_register() is repeated:
- Other code in
functions.php, in a plugin's main file or inapp/incruns once per process. AView::composer()or a Blade directive declared there exists in the first application only: put it in a service provider of the theme or plugin. - A direct call to the theme or plugin registrar is not repeated.
- A callback that a registration hooks into another action fired while WordPress loads is not run again.
Before 13.45.2, only the first application of a test process has the theme: on a fresh skeleton, view()->exists('index') is false from the second test on.
WordPress hooks are globals too. Each feature test gets a new application, but WordPress is loaded once per process, and the callbacks that an application registered stay in $wp_filter after Laravel has flushed it at the end of its test. When a later test fires the hook, a callback of the first application asks that flushed container for a service. Two feature tests show it:
// tests/Feature/FirstTest.php: any test that boots the application
it('boots the application', function (): void {
expect(function_exists('post_type_exists'))->toBeTrue();
});// tests/Feature/FooterTest.php
it('runs the footer hooks', function (): void {
ob_start();
do_action('wp_footer');
ob_end_clean();
expect(true)->toBeTrue();
});FooterTest passes when it runs alone. Run after FirstTest it fails with Target [Pollora\Theme\Domain\Contracts\ThemeJsonResolverInterface] is not instantiable., thrown from do_action() through WP_Hook::apply_filters(). The message does not point at the cause, and the test passes alone, so it looks flaky. A hook a test adds itself also stays: two tests that each call Action::add('my_event', …) with the same handler make the second one run it twice.
There are several ways around it.
Use the framework's trait (Pollora 13.45.2 and later). Add it to the base test case; Laravel sets it up and tears it down, under Pest too:
// tests/TestCase.php
declare(strict_types=1);
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Pollora\Testing\IsolatesWordPressHooks;
abstract class TestCase extends BaseTestCase
{
use IsolatesWordPressHooks;
}After each test, $wp_filter, $wp_actions and $wp_filters go back to what loading WordPress left. What the application or the test hooked is removed, with add_action() as with the facades. What WordPress, plugins, must-use plugins and functions.php hooked while loading is kept, as are the static methods hooked while the application booted and what pollora/roles and pollora/schedule hook once per process.
Put it on every test that boots the application. Know its limits:
- It restores hooks only. Other static properties, WordPress globals, constants and the database carry over.
- It does not register anything. The theme and the plugins that call
pollora_register()are registered again in each application by the framework itself, see Themes and plugins in tests. - A hook added by a file that PHP includes for the first time during a test is removed with the test and does not come back.
- A closure that a file loaded once wrote, and objects of your own classes hooked while WordPress loaded, are kept: if they hold the first application, they still do.
- The load is recorded only when
APP_ENVistesting. Otherwise each test only gets back the hooks it started with.
Call the method, not the hook. (new ShowBanner())->handleWpFooter() fires no action and does not meet the problem.
Remove the hooks yourself, before Pollora 13.45.2. This works under Pest. Put it in the skeleton's tests/TestCase.php, which tests/Pest.php binds to every test under tests/Feature:
// tests/TestCase.php
declare(strict_types=1);
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Pollora\Hook\Domain\Contract\Action;
use Pollora\Hook\Domain\Contract\Filter;
abstract class TestCase extends BaseTestCase
{
private array $wordPressHooks = [];
protected function setUp(): void
{
parent::setUp();
$this->wordPressHooks = array_map(fn ($hook) => clone $hook, $GLOBALS['wp_filter'] ?? []);
}
protected function tearDown(): void
{
if ($this->wordPressHooks !== []) {
// Drops what the test added.
$GLOBALS['wp_filter'] = $this->wordPressHooks;
// Drops what its application registered through Action and Filter, #[Action] and #[Filter] included.
foreach ([Action::class, Filter::class] as $contract) {
foreach ($this->app->make($contract)->all() as $hook => $registrations) {
foreach ($registrations as $registration) {
remove_filter($hook, $registration['callback'], $registration['priority']);
}
}
}
$this->wordPressHooks = [];
}
parent::tearDown();
}
}It is not a full isolation. Know its limits:
- A callback that a boot adds with WordPress's own
add_action()oradd_filter()stays. On a fresh skeleton v13.45.0 five remain per application, added by the framework and its packages oninit,wp_head,admin_notices,network_admin_noticesandtemplate_include. Firinginit,wp_head,admin_noticesandnetwork_admin_noticesand applyingtemplate_includein later tests raised no error. (In a console test,wp_headalso needs the server variables thatWordPressTestCasesets: without them WordPress stops withUndefined array key "SERVER_NAME".) The sameadd_action()in your own service provider would stay too. - A hook registered through the
ActionorFilterfacade by a file that PHP loads only once, such as a must-use plugin, is removed after the first test and does not come back. One added by such a file withadd_action()stays. - Only
$wp_filteris handled:did_action()counts, constants and other globals carry over.
Run the test in its own process. For a clean WordPress in each test, write a PHPUnit class with the two attributes, outside the suites of phpunit.xml, and run it with vendor/bin/phpunit tests/Isolated, like UnknownUrlTest above:
// tests/Isolated/FooterTest.php
namespace Tests\Isolated;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use Tests\TestCase;
#[RunTestsInSeparateProcesses]
#[PreserveGlobalState(false)]
final class FooterTest extends TestCase
{
public function test_the_application_boots(): void
{
$this->assertTrue(function_exists('post_type_exists'));
}
public function test_the_footer_hooks_run(): void
{
ob_start();
do_action('wp_footer');
ob_end_clean();
$this->assertTrue(true);
}
}With the skeleton's unchanged TestCase and without the two attributes, the second test fails with the error above. composer test does not run this directory: add vendor/bin/phpunit tests/Isolated to your CI job. To keep Pest syntax, the other option is one php artisan test <file> run per file; tests of the same file still share a process.
| What | Helper | Documented in |
|---|---|---|
| Asynchronous actions | Async::fake() records what would be queued; assertDispatched(), assertDispatchedTimes(), assertNotDispatched(), assertNothingDispatched() |
Asynchronous Actions, Testing |
| Scheduler | Schedule::fake() records events and attaches no handler; assertScheduled(), assertScheduledTimes(), assertNotScheduled(), assertNothingScheduled(); Schedule::reset() brings the real driver back |
Scheduling, Testing |
| Options | Pollora\Option\Domain\Contract\OptionRepositoryInterface (get, store, update, delete, exists), to mock or to replace |
Options, Unit Testing |
The two fakes work in a feature test, with no wp() call. This test queues an asynchronous action and checks it without running it, then runs it (SyncToCrm and SendDigest below are classes of your own with a handle() method):
// tests/Feature/SyncToCrmTest.php
use App\Crm\SyncToCrm;
use Pollora\Hook\Async\Async;
use Pollora\Hook\Async\AsyncPayload;
use Pollora\Support\Facades\Action;
it('queues the handler, then runs it', function (): void {
$fake = Async::fake();
Action::add('my_event', [SyncToCrm::class, 'handle'])->async()->delay(60);
do_action('my_event', 7);
Async::assertDispatched(SyncToCrm::class, fn (AsyncPayload $payload, int $delay): bool => $delay === 60);
Async::assertDispatchedTimes(SyncToCrm::class, 1);
$fake->runDispatched();
});The test registers a hook: a second test registering the same handler on my_event fails with was dispatched 2 time(s) instead of 1, unless the hooks are removed after each test or the two use different hook names.
runDispatched() is a method of the object Async::fake() returns, not of the Async class.
For the scheduler:
// tests/Feature/DigestTest.php
use App\Crm\SendDigest;
use Pollora\Schedule\Event;
use Pollora\Schedule\Schedule;
it('schedules a digest', function (): void {
Schedule::fake();
Schedule::once('send_digest')->in(minutes: 10)->with(['user' => 42])->call(SendDigest::class);
Schedule::assertScheduled('send_digest', fn (Event $event) => $event->args === ['user' => 42]);
Schedule::assertNotScheduled('send_survey');
Schedule::reset();
});Call Schedule::reset() at the end of a test that faked the scheduler: the fake stays in place until it is reset.
The job needs what the tests need: PHP 8.3 or later, the Composer dependencies, a .env, a database, and an installed WordPress. The skeleton's own workflow (.github/workflows/tests.yml) does this, in order:
composer install --no-interaction --no-progress
php artisan key:generate --no-interaction
php artisan pollora:install --install --title="…" --description="…" \
--admin-user=admin --admin-email=admin@example.com --admin-password="…" \
--locale=en_US --public=false --no-interaction
composer testwith a .env copied from .env.example and its DB_* lines pointed at the job's database. pollora:install creates the WordPress tables that the shipped Feature/Installation tests read.
APP_ENV=testing comes from phpunit.xml, as above.
Add the doctor after the tests:
php artisan pollora:doctorpollora:doctor checks the project for failures that leave the site rendering: a missing Composer patches lock, a stale discovery cache, a theme without its Vite build, an ignored #[Async], and the others listed in Diagnosing a project. It exits 0 when no check finds an error (warnings do not change that) and 1 when one does, so the job fails on its own. --json prints the report for a script, and exits with the same code. Run it in the job that builds the project, after the theme's npm run build, since it also looks for the builds. The checks that need a web request, such as the document root, run in Tools › Site Health, not in the console.
- Asynchronous Actions —
Async::fake() - Scheduling —
Schedule::fake() - Options —
OptionRepositoryInterface - Dashboard & Status —
pollora:doctor - Local Development Environments — a database and a server for the project
- Performance Gates — the framework's query budgets and nightly measures