views:

388

answers:

2

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?

+1  A: 

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'));
Gordon
Thanks for the link, but I'm unfortunately not on 5.3 as of yet.
rr
+1  A: 

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 :

class Model_User extends Doctrine_Record
{
    public function saveFromArray($userData)
    {
        $this->fromArray($userData);
        $this->save();
    }
}

Not sure what you'll be testing ; but, at least, no static method anymore...

Pascal MARTIN
Thanks for the suggestion, it's more style than anything. I could make the method non static in this particular instance (though I'd prefer being able to use it without instantiating).
rr