Using PHPUnit to test WordPress functions ($wpdb)

I’m writing a WordPress theme. There is some backend class that talks to the SQL database through $wpdb variable (“sql-connector.php”). In the WordPress theme, some page would include this php page and create a db_connector object, in which I could just use global $wpdb right away.

sql-connector.php:

Read More
<?php

class db_connector {

function verify_account($em, $pwd) {
    global $wpdb; 

    echo "em = ". $em;
    echo "pwd = ". $pwd; 

    $query = 
        "
        SELECT id
        FROM data_customers
        WHERE email = %s AND password = %s
        ";

    /* customer_id */               
    $result = $wpdb->get_var($wpdb->prepare($query, $em, $pwd));

    echo "empty? = ".!empty($result);

    return $result;
}

}?>

Now I want to use PHPUnit to test the function verify_account($em, $pwd). I use the code below.

sql-connectorTest.php:

<?php

include("sql-connector.php");

class db_connectorTest extends PHPUnit_Framework_TestCase{
    private $db_connector;

    function testVerify_account() {
        $db_connector = new db_connector();

        $result = $db_connector->verify_account("username@email.com", md5("password"));

        $this->assertEmpty($result);
    }


}

?>

Running PHPUnit, it would only give the following results:

MacBruce:model bruce$ phpunit sql-connectorTest.php
PHPUnit 3.7.22 by Sebastian Bergmann.

em = username@email.compwd = 5f4dcc3b5aa765d61d8327deb882cf99MacBruce:model bruce$ 

It seems that it stuck when it wants to use the $wpdb->get_var(...) function. It seems that the $wpdb is empty.

I’m very new to PHPUnit and WordPress. Did I miss to include any WordPress/PHPUnit libraries? Or did I miss to include some of my own php files?

Thank you.

Related posts

Leave a Reply

2 comments

  1. You need an active connection to the database ($wpdb), instantiated with all credentials,
    then use it in your test. Try to avoid globals, pass it in the constructor or in setter.

    Also, you may want to look at some ready to go wordpress testing tools like http://wptest.io/

  2. I’ve just set up PHPUnit & WP. The trick is that it needs its own install of the WordPress source files, and its own database instance, but then can set up & tear down test environments.

    I used these guides:

    One warning is that PHPUnit can serialise $wpdb unless you tell it not to, and that will also mess up your db connection.