Function Mocker 0.2.15

I’ve released a new version of function-mocker aimed at test uniformity with added sugar methods.

Test method wrapping

I’ve taken the habit to alias the tad\FunctionMocker\FunctionMocker class to the Test name (not an idea of mine) and I like the clean and readable code that generates

use tad\FunctionMocker\FunctionMocker as Test; class SomeTest extends \PHPUnit_Framework_TestCase { public function test_dependency_is_called() { $dependency = Test::replace('Dependency::someMethod', 23); $sut = new Client(); $sut->setDependency($dependency); $sut->callDependency(); $dependency->wasCalledOnce('someMethod'); Test::assertEquals(23, $sut->getDependencyReturnValue()); } } 

while that’s totally sudo code I think it pushes the idea through and the use of the Test alias makes test reading easier.
I’ve also blatantly copied another good idea and made test methods available on the FunctionMocker class; that’s nothing but a wrapping of a PHPUnit_Framework_TestCase and some call forwarding; in place of using magic methods I’ve gone the trait road to trigger auto-completion of the standard test case method signatures on capable IDEs like PhpStorm and Sublime Text.

Global replacement

Working with WordPress code the need might arise to replace a globally shared value or object with a mock or ad-hoc one: having grown tired of manually replacing and restoring such objects I’ve added the replaceGlobal and setGlobal methods to the package. To give an example test code like this

use tad\FunctionMocker\FunctionMocker as Test; class SomeTest extends \PHPUnit_Framework_TestCase { public function test_will_return_false_if_no_post() { $wpdb = Test::replace('wpdb::get_results', []); $wpdb->posts = 'wp_posts'; // save global state $prevWpdb = $GLOBALS['wpdb']; // replace global $GLOBALS['wpdb'] = $wpdb; $sut = new PostRepository(); $post = $sut->find(23); $query = "SELECT * from wp_posts WHERE ID = '23'"; $wpdb->wasCalledWithOnce([$query, ARRAY_A], 'get_results'); Test::assertEquals(false, $post); //restore global var $GLOBALS['wpdb'] = $prevWpdb; } } 

could be rewritten like this

use tad\FunctionMocker\FunctionMocker as Test; class SomeTest extends \PHPUnit_Framework_TestCase { public function test_will_return_false_if_no_post() { $wpdb = Test::replaceGlobal('wpdb::get_results', []); $wpdb->posts = 'wp_posts'; $sut = new PostRepository(); $post = $sut->find(23); $query = "SELECT * from wp_posts WHERE ID = '23'"; $wpdb->wasCalledWithOnce([$query, ARRAY_A], 'get_results'); Test::assertEquals(false, $post); } } 

the $wpdb global will be restored in the FunctionMocker::tearDown method. That might be redundant over PHPUnit @backupGlobals annotation but my personal taste is to have it written in methods.

On GitHub

The improvements above and some bug-fixing I’ve pushed to GitHub on version tagged 0.2.15.

I appreciate your input