Home » Wordpress » Using PHPUnit to test WordPress functions ($wpdb)

Using PHPUnit to test WordPress functions ($wpdb)

Posted by: admin November 30, 2017 Leave a comment

Questions:

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:

<?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("[email protected]", 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 = [email protected] = 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.

Answers:

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/