Unit Testing
Unit Testing
Ensuring the stability and reliability of our WordPress contributions is paramount. This project utilizes PHPUnit combined with the official WordPress Test Suite to perform integration and unit testing.
Prerequisites
Before running tests, ensure your local environment meets the following requirements:
- PHP: 7.4 or higher.
- Composer: For managing PHPUnit and dependencies.
- MySQL/MariaDB: A dedicated database for testing (data will be deleted frequently).
- Subversion (svn): Required to fetch the WordPress test library.
Setup
To initialize the testing environment, you must install the WordPress test suite and configure your test database.
-
Install Dependencies:
composer install -
Initialize Test Suite: Run the included setup script to download the WordPress source and configure the test database.
# Usage: bin/install-wp-tests.sh <db-name> <db-user> <db-pass> [db-host] [wp-version] bin/install-wp-tests.sh wp_test_db root password localhost latestNote: This script will create a temporary directory and a database. Ensure the database user has permissions to create/drop tables.
Running Tests
You can execute the full test suite or target specific files/groups using the vendor-supplied PHPUnit binary.
Run all tests:
vendor/bin/phpunit
Run a specific test file:
vendor/bin/phpunit tests/test-example.php
Run tests with a specific group tag:
vendor/bin/phpunit --group ajax
Writing Test Cases
All test classes should reside in the tests/ directory and extend the WP_UnitTestCase class. This class provides WordPress-specific utilities, such as factory methods for creating posts, users, and taxonomies that are automatically cleaned up after each test.
Example Test Case
class Test_Sample_Plugin extends WP_UnitTestCase {
/**
* Verify that our custom filter modifies the content as expected.
*/
public function test_content_filter() {
$content = "Hello World";
$filtered = apply_filters('my_custom_filter', $content);
$this->assertEquals('Hello World - Modified', $filtered);
}
/**
* Test post creation using the WordPress Factory.
*/
public function test_post_creation() {
$post_id = $this->factory->post->create([
'post_title' => 'Test Post',
'post_status' => 'publish'
]);
$post = get_post($post_id);
$this->assertEquals('Test Post', $post->post_title);
}
}
Key Components
| Tool | Purpose |
| :--- | :--- |
| WP_UnitTestCase | The base class for all tests. It resets the WordPress state between tests. |
| $this->factory | Provides objects (post, user, comment, term) for quick data generation. |
| phpunit.xml | Configuration file defining test suites, environment variables, and coverage reporting. |
Best Practices
- Isolation: Never run tests against a production database.
- Assertions: Use specific PHPUnit assertions (e.g.,
assertWPError()) when dealing with WordPress core objects. - Cleanup: While
WP_UnitTestCasehandles most cleanup, ensure any manual changes to the filesystem or global variables are reverted in thetearDown()method.