Minimum Requirements:
Open your terminal and go to your plugin/theme’s root directory
cd wordpress/wp-content/plugins/<your-plugin>/
Run the wp scaffold command:
wp scaffold plugin-tests <plugin-name>
This should create 2 directories and 1 file
Run bin/install-wp-tests.sh
You need to provide the following arguments for it to run:
There is some issue when using zsh shell with the LocalWP, the best way is to execute the below script with the shell you are using.
For bash shell:
bash ./bin/install-wp-tests.sh <db-name> <db-user> <db-pass> [db-host] [wp-version]
For zsh shell:
zsh ./bin/install-wp-tests.sh <db-name> <db-user> <db-pass> [db-host] [wp-version]
<db-name> - Name of the test database you created.
<db-user> - User of the database.
<db-pass> - Password of the Database user.
[db-host] - Host of the database (Usually localhost).
[wp-version] - WordPress version to download to run the tests.
This will create a test database and create a new WordPress installation in /tmp
If your WP-CLI verison is same or higher than 2.10.0, you can directly go to the step 3.
Run the following command, to get the WP CLI version.
wp --version
Note: For Local by Flywheel, you need to edit ./install-wp-test.php to make it work with WPLocal’s DB, basically adding full –user & –password parameters to make it compatible with the WPLocal site shell.
Make the following changes
Change 1:
In recreate_db() function
Replace with
mysqladmin drop $DB_NAME -f --user="$DB_USER" --password="$DB_PASS"$EXTRA
Change 2:
In create_db() function
Replace with
mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA
Change 3:
In install_db() function
Replace with
mysql --user="$DB_USER" --password="$DB_PASS"$EXTRA --execute='show databases;' | grep ^$DB_NAMES
Install phpunit
as project dependencies:
composer require --dev phpunit/phpunit
The latest version of the PHPUnit will installed, which may not work properly. Go through this chart https://make.wordpress.org/core/handbook/references/phpunit-compatibility-and-wordpress-versions/, and update the PHPUnit version in the composer.json file
Install Yoast PHPUnit polyfills:
composer require --dev yoast/phpunit-polyfills:"^2.0"
Comment out the excluded test from the phpunit.xml.dist file.
<?xml version="1.0"?>
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<php>
<env name="WP_TESTS_PHPUNIT_POLYFILLS_PATH" value="vendor/yoast/phpunit-polyfills" />
</php>
<testsuites>
<testsuite name="testing">
<directory prefix="test-" suffix=".php">./tests/</directory>
<!-- <exclude>./tests/test-sample.php</exclude> -->
</testsuite>
</testsuites>
</phpunit>
Run in plugin root:
./vendor/bin/phpunit
Output:
References: