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

查看:30
本文介绍了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 和 Mocking 静态方法.使用 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天全站免登陆