模拟/存根在PHPUnit中实现arrayaccess的类的对象 [英] Mocking/Stubbing an Object of a class that implements arrayaccess in PHPUnit

查看:60
本文介绍了模拟/存根在PHPUnit中实现arrayaccess的类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在为其编写测试套件的类的构造函数(它扩展了mysqli):

Here is the constructor of the class I am writing a test suite for (it extends mysqli):

function __construct(Config $c)
{
    // store config file
    $this->config = $c;

    // do mysqli constructor
    parent::__construct(
        $this->config['db_host'],
        $this->config['db_user'],
        $this->config['db_pass'],
        $this->config['db_dbname']
    );
}

传递给构造函数的Config类实现了内置于php的arrayaccess接口:

The Config class passed to the constructor implements the arrayaccess interface built in to php:

class Config implements arrayaccess{...}

如何模拟/存根Config对象?我应该使用哪个?为什么?

How do I mock/stub the Config object? Which should I use and why?

提前谢谢!

推荐答案

如果您可以轻松地从数组创建Config实例,那将是我的偏爱.当您想在可行的情况下单独测试单元时,简单的协作者(例如Config)应该足够安全,可以在测试中使用.设置它的代码可能比等效的模拟对象更容易读写(较少出错).

If you can easily create a Config instance from an array, that would be my preference. While you want to test your units in isolation where practical, simple collaborators such as Config should be safe enough to use in the test. The code to set it up will probably be easier to read and write (less error-prone) than the equivalent mock object.

$configValues = array(
    'db_host' => '...',
    'db_user' => '...',
    'db_pass' => '...',
    'db_dbname' => '...',
);
$config = new Config($configValues);

话虽如此,您模拟了一个实现 ArrayAccess 的对象,就像你会其他任何物体.

That being said, you mock an object implementing ArrayAccess just as you would any other object.

$config = $this->getMock('Config', array('offsetGet'));
$config->expects($this->any())
       ->method('offsetGet')
       ->will($this->returnCallback(
           function ($key) use ($configValues) {
               return $configValues[$key];
           }
       );

您还可以使用at来强加特定的访问顺序,但是那样会使测试变得非常脆弱.

You can also use at to impose a specific order of access, but you'll make the test very brittle that way.

这篇关于模拟/存根在PHPUnit中实现arrayaccess的类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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