Plugin Unit Test for Table and Option Creation

Should you test this? Yes.

How should you test this? That depends.

There are several different approaches to unit testing WordPress plugins. The one that I prefer and am most familiar with is more like integration testing. I can’t tell from your post whether you are using this approach or not, but I’ll answer from this perspective anyway.

For my own plugins, I’ve created a base testcase that will help you do this. It let’s you test installation, and uninstallation as well, and provides some custom assertions that you’ll probably find useful.

From the readme:

The purpose of this testcase is to allow you to make plugin uninstall testing as realistic as possible. WordPress uninstalls
plugins when they aren’t active, and these tools allow you simulate
that. The installation is performed remotely, so the plugin is not
loaded when the tests are being run.

I created these tools after finding that there was a fatal error in
one of my plugin’s uninstall scripts. Not that I didn’t have unit
tests for uninstallation. I did. But the uninstall tests were being
run with the plugin already loaded. So I never realized that I was
calling one of the plugin’s functions that wouldn’t normally be
available. That’s when I decided to create these testing tools, so my
uninstall tests would fail if I wasn’t including all required
dependencies in my plugin’s uninstall script.

In addition to providing a realistic uninstall testing environment, it
also provides some assertions to help you make sure that your plugin
entirely cleaned up the database.

An portion of an example testcase, also from the readme:

    /**
     * Test installation and uninstallation.
     */
    public function test_uninstall() {

        /*
         * First test that the plugin installed itself properly.
         */

        // Check that a database table was added.
        $this->assertTableExists( $wpdb->prefix . 'myplugin_table' );

        // Check that an option was added to the database.
        $this->assertEquals( 'default', get_option( 'myplugin_option' ) );

        /*
         * Now, test that it uninstalls itself properly.
         */

        // You must call this to perform uninstallation.
        $this->uninstall();

        // Check that the table was deleted.
        $this->assertTableNotExists( $wpdb->prefix . 'myplugin_table' );

        // Check that all options with a prefix was deleted.
        $this->assertNoOptionsWithPrefix( 'myplugin' );

        // Same for usermeta and comment meta.
        $this->assertNoUserMetaWithPrefix( 'myplugin' );
        $this->assertNoCommentMetaWithPrefix( 'myplugin' );
    }

Edit (Thu Jan 22 2015 3:28 PM):

Even if you don’t want to go all out and adopt this approach fully, you can probably still find some useful bits in it that will give you an idea of what is needed to test table creation, etc.

Leave a Comment