Last active
December 14, 2015 16:59
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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