Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Mock Objects and Static Methods

I am looking for the best way to go about testing the following static method (specifically using a Doctrine Model):

class Model_User extends Doctrine_Record {     public static function create($userData)     {         $newUser = new self();         $newUser->fromArray($userData);         $newUser->save();     } } 

Ideally, I would use a mock object to ensure that fromArray (with the supplied user data) and save were called, but that's not possible as the method is static.

Any suggestions?

like image 260
rr. Avatar asked Mar 01 '10 15:03

rr.


2 Answers

Sebastian Bergmann, the author of PHPUnit, recently had a blog post about Stubbing and Mocking Static Methods. With PHPUnit 3.5 and PHP 5.3 as well as consistent use of late static binding, you can do

$class::staticExpects($this->any())       ->method('helper')       ->will($this->returnValue('bar')); 

Update: staticExpects is deprecated as of PHPUnit 3.8 and will be removed completely with later versions.

like image 129
Gordon Avatar answered Sep 29 '22 10:09

Gordon


There is now the AspectMock library to help with this:

https://github.com/Codeception/AspectMock

$this->assertEquals('users', UserModel::tableName());    $userModel = test::double('UserModel', ['tableName' => 'my_users']); $this->assertEquals('my_users', UserModel::tableName()); $userModel->verifyInvoked('tableName');  
like image 43
treeface Avatar answered Sep 29 '22 08:09

treeface