Skip to content
This repository has been archived by the owner on Jul 12, 2024. It is now read-only.

Running PHP unit tests

Ilyas Foo edited this page Dec 22, 2020 · 12 revisions

Using Docker

npm run test:php

Further information can be found in the README.

Using VVV or Similar

Running PHP unit tests locally requires a bit of set-up, so this is how it worked for me.

Pre-requisites:

  • PHP 7.1+ (see footnotes 2 and 3)
  • composer
  • running mysql with user $MYSQL_USER and password $MYSQL_PASSWD that can create/alter databases
  • wc_admin checked out in $WC_ADMIN_DIR (e.g. /srv/www/wordpress-default/public_html/wp-content/plugins/wc-admin if within VVV2)
  • woocommerce development environment in $WC_ADMIN_DIR/../woocommerce. Here's how to set it up

Please note that database $DB_NAME will be dropped during this script, created again and erased on each test run.

Script:

export WC_ADMIN_DIR=/srv/www/wordpress-default/public_html/wp-content/plugins/wc-admin
export WP_TESTS_DIR=/tmp/wordpress-tests-lib
export WP_CORE_DIR=/tmp/wordpress
export DB_NAME=wc_admin_test
export MYSQL_USER=root
export MYSQL_PASSWD=root

cd $WC_ADMIN_DIR
composer install
./bin/install-wp-tests.sh $DB_NAME $MYSQL_USER $MYSQL_PASSWD localhost latest
cd $WC_ADMIN_DIR
./vendor/bin/phpunit

After this setup step has finished, it should be sufficient to run unit tests just by running


cd $WC_ADMIN_DIR
./vendor/bin/phpunit

This should run the unit tests using code in $WC_ADMIN_DIR against database $DB_NAME.

To run only one test file, you can specify the file path for phpunit, e.g.:


cd $WC_ADMIN_DIR
./vendor/bin/phpunit tests/reports/class-wc-tests-reports-orders.php

Footnotes:

  1. normally, WP_CORE_DIR and WP_TESTS_DIR are defined differently in VVV (pointed to /srv/www/wordpress-develop/public_html/src/ and /srv/www/wordpress-develop/public_html/tests/phpunit/, respectively), so this set up should not interfere/affect normal testing setup installation you may have on VVV.
  2. Similarly to WooCommerce, composer install only works for PHP 7.1+. For older PHP versions, it's probably best to install phpunit required for given PHP version and add it to PATH, then run phpunit instead of ./vendor/bin/phpunit
  3. PHPUnit v7 would not work with wc-admin, as some classes in WC tests inherit from a class that was made final in PHPUnit v7.