Skip to content

Instantly share code, notes, and snippets.

@dbernar1
Last active December 14, 2015 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbernar1/5119400 to your computer and use it in GitHub Desktop.
Save dbernar1/5119400 to your computer and use it in GitHub Desktop.
A way to provide a test double for WordPress globals, like $wpdb, in order to unit test functions that use the global.
<?php
class TestDouble {
private $stubs;
public function stub( $method_name, $return_value ) {
$this->stubs[ $method_name ] = $return_value;
}
public function __call( $method_name, $args ) {
if ( isset( $this->stubs[ $method_name ] ) ) {
return $this->stubs[ $method_name ];
}
}
public function __get( $property_name ) {
}
}
$wpdb = new TestDouble();
require_once('simpletest/autorun.php');
class WPTest extends UnitTestCase {
function test_db_key_is_a_valid_key() {
global $wpdb;
// returns true when the key is in the database
$wpdb->stub(
$method = 'get_var',
$will_return = '2'
);
$this->assertTrue( db_key_is_a_valid_key( 'invalid_key' ) );
//returns false when the key is not in the database
$wpdb->stub(
$method = 'get_var',
$will_return = null
);
$this->assertFalse( db_key_is_a_valid_key( 'valid_key' ) );
}
}
function db_key_is_a_valid_key( $key ) {
global $wpdb;
$id_of_site_record_belonging_to_provided_home_url = $wpdb->get_var( $wpdb->prepare(
"SELECT ID FROM " . $wpdb->prefix . "sites WHERE site_key = %s",
$key
) );
return ! empty( $id_of_site_record_belonging_to_provided_home_url );
}
@dbernar1
Copy link
Author

dbernar1 commented Mar 8, 2013

Here I'm unit testing the db_key_is_a_valid_key function.

It is a boolean function, which returns whether a provided key is a valid one or not.

Whether the function returns true or false is dependent on the return value of the $wpdb->get_var function, so that return value needs to be stubbed out to stimulate each possible case.

The get_var method of the wpdb class returns

  • null if for whatever reason the DB query does not return any rows, including if the query is malformed.
  • a single value if the query returns rows

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment