Unit Testing in WordPress

Unit testing in PHP is one of those things that people talk about but can be difficult to get your head around until you take the leap and actually write your first test.

It can also be difficult to see the value in taking the time to write tests if you’ve never done it before, but take my word for it – it’s one of those things that when you start writing tests you’ll wonder why the hell it took you so long to start writing tests and how you ever managed before!

I can pretty much guarantee you it will make you change the way you structure your code too, in my case very much for the better.

Getting started

First you’ll need to install PHPUnit.

composer global require phpunit/phpunit

The easiest way to add tests to a plugin is to use WP-CLI.

wp scaffold plugin-tests {plugin-name}

Check out the documentation for more details about this command.

When you’ve run the command, cd to your plugin directory and run.

./bin/install-wp-tests.sh {db-name} {db-user} {db-pass} [db-host] [wp-version] [skip-database-creation]

Just run something like the following:

./bin/install-wp-tests.sh wordrpress_tests mysql_username mysql_password

To install the test library and the tests database. Do not use a real database for this as it will be deleted when you run your tests!!

Writing your tests

Alright, you’ve made it this far! You’ll notice a couple of files added to your plugin now. Check out the default tests class at: tests/tests-sample.php. It should look like this:

/**
 * Sample test case.
 */
class SampleTest extends WP_UnitTestCase {

    /**
     * A single example test.
     */
    function test_sample() {
        $this->assertTrue( true );
    }
}

If you run

phpunit

from your plugin directory you should see something like the following:

Unit tests result

Awesome brah!! Now you just need to write some actual tests. Sitepoint has a pretty good introduction article about this. I suggest just playing around with the API it feels natural.

Try adding the following to your tests class and see what happens :)

function test_something() {
    $string = 'Nice :)';
    $this->assertEquals( 'Nice :)', $string );
}

function test_something_that_fails() {
    $string = 'Nice :)';
    $this->assertEquals( 'BAD :(', $string );
}

There’s a bunch of assertions you can use depending on your use case. They’re all detailed on the PHPUnit site.

Happy testing!

Update! I’ve since written a sort of part 2 to this post that goes a bit deeper into how to integrate your tests with WordPress and even other plugins. Check it out, if you fancy diving a wee bit deeper into the subject.