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?
There is now the AspectMock library to help with this:
https://github.com/Codeception/AspectMock
I would make a new class in the unit test namespace that extends the Model_User and test that. Here's an example:
Original class:
Mock Class to call in unit test(s):
In your unit test:
The doublit library could also help you to test static methods :
Testing static methods is generally considered as a bit hard (as you probably already noticed), especially before PHP 5.3.
Could you not modify your code to not use static a method ? I don't really see why you're using a static method here, in fact ; this could probably be re-written to some non-static code, could it not ?
For instance, could something like this not do the trick :
Not sure what you'll be testing ; but, at least, no static method anymore...
Another possible approach is with the Moka library:
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
Update:
staticExpects
is deprecated as of PHPUnit 3.8 and will be removed completely with later versions.