PHPUnit模拟对象和静态方法 [英] PHPUnit Mock Objects and Static Methods

查看:130
本文介绍了PHPUnit模拟对象和静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最好的方法来测试以下静态方法(具体使用的是Doctrine模型):

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();
    }
}

理想情况下,我会使用模拟对象来确保调用fromArray(带有提供的用户数据)和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.

任何建议?

推荐答案

PHPUnit的作者Sebastian Bergmann最近有一篇关于 Stubbing and Mocking Static Methods 。使用PHPUnit 3.5和PHP 5.3以及一致使用后期静态绑定,您可以执行

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'));

更新: staticExpects 不推荐使用PHPUnit 3.8 ,并将在以后的版本中完全删除。

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

这篇关于PHPUnit模拟对象和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆