PHPUnit Tests for WordPress Plugins: Global Variables

by Daniel Convissor at 2012-11-05 10:00:00

Creating the Login Security Solution taught me a lot about designing clean, solid WordPress plugins. It seemed like a good idea to distill those concepts into a skeleton that other developers can use for creating or augmenting their own plugins. So please raise a toast for the Object Oriented Plugin Template Solution. Now I'll throw some more logs under the boiler to extract a few essences into some quick tutorials.

The initial posts will cover unit testing WordPress plugins with PHPUnit. This first article shows how to work around the conflict between WordPress' heavy reliance on globally scoped variables (groan) and PHPUnit's squashing of global variables. This mayhem results in several errors:

Place this at the top of the script that sets up the environment:

global $current_blog, $current_site, $wp_rewrite, $wpdb;
$_SERVER['HTTP_HOST'] = 'localhost';

Add this property to your parent test case class that extends PHPUnit_Framework_TestCase:

protected $backupGlobals = false;

Now require_once the wp-load.php file and you're good to go.

To examine the full framework, download the Object Oriented Plugin Template Solution from WordPress' plugin directory.

Tags: wordpress, phpunit, php

View all posts

Email me a comment:

(I'll append it here when I get a chance.)