Getting started with PHP tests
Local Development
If Starting from scratch
- Download a zip from the
cno-starter-themeor start a new Github repo with that as the template. - Migrate all files to a fresh Local WP site (including the
.gitfolder if it exists) - Follow the readme to get the theme started.
If starting on an existing repo
- Create a
binfolder inside the theme folder and add 2 files:install-wp-tests.shandlocal-mysql-socket.sh - Copy the contents from the Github Template Theme repo
- Update
composer.jsonto include the following key/value pairs:autoload-devscripts.testandscripts.install-tests- Update the path to be your theme name (from
cno-starter-themetoyour-theme-name) require-dev: add the missing packages (phpunit&yoast/phpunit-polyfills
- Run
composer update -wto update/install new dependencies - Add
.wp-teststo your.gitignore
# .gitignore
# ...rest of .gitignore...
# Tests
.wp-tests/Enabling Code Coverage
- In Local, click on
Site Folder, then navigate toconf/php/php.ini.hbs. - Open the file with TextEditor (VS Code autoformat can royally screw things up) and find the following:
# conf/php/php.ini.hbs
{{#if xdebugEnabled}}
xdebug.mode=debug,develop- Add ‘coverage’ as the third item in the list
# conf/php/php.ini.hbs
{{#if xdebugEnabled}}
xdebug.mode=debug,develop,coverage- Add the resulting new files to `.gitignore
# .gitignore
# ...rest of .gitignore...
# Tests
.wp-tests/
.phpunit.result.cache
.phpunit.cache
html-coverage/Init Test Suite Locally
- Click the
Site Shellbutton on a local WP site - Run
wp scaffold theme-tests [theme-name]- When you see
Warning: file already exists, skip the file - Delete / move the
.circle-cifolder,.phpcs.xml.distfile, andphpunit.xml.dist(if you need thephpunitxml, copy it from the template repo and place it in the root of the repo (/public). Be sure to update the theme name if doing so!
- When you see
- Run
composer install-tests - Run
composer test
Weirdness
- PHPUnit must run version
^9until things get updated (which you can track here)—even though PHPUnit is on v12 (at time of writing). - The final lines of
install-wp-tests.shsymlink the WordPress tests directory so PHP intelephense knows about the test classes (no more red squigglies). You should see a.wp-tests/wordpress-tests-libfolder with/data,/includes, awp-tests-config.phpfile and awp-tests-config.php.bakfile.- If you see these and see red squigglies, reload the window (VS Code Command Palette (
Cmd + Shift + P) then"Developer: Reload Window")
- If you see these and see red squigglies, reload the window (VS Code Command Palette (
Further Reading
- WordPress docs on Writing PHP Tests
- WP_UnitTestCase_Base code
- Udemy Course on PHPUnit
- PHPUnit Docs