Mocking/Stubbing在PHPUnit中实现arrayaccess的类的Object

And*_*tch 8 php phpunit arrayaccess

这是我正在编写测试套件的类的构造函数(它扩展了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']
    );
}
Run Code Online (Sandbox Code Playgroud)

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

class Config implements arrayaccess{...}
Run Code Online (Sandbox Code Playgroud)

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

提前致谢!

Dav*_*ess 16

如果您可以轻松地Config从数组创建实例,那将是我的偏好.虽然您希望在实际Config情况下单独测试您的设备,但是简单的协作者应该足够安全以便在测试中使用.设置它的代码可能比等效的模拟对象更容易读写(更不容易出错).

$configValues = array(
    'db_host' => '...',
    'db_user' => '...',
    'db_pass' => '...',
    'db_dbname' => '...',
);
$config = new Config($configValues);
Run Code Online (Sandbox Code Playgroud)

话虽这么说,你嘲笑一个ArrayAccess像任何其他对象一样实现的对象.

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

您也可以使用at强制执行特定的访问顺序,但这样会使测试变得非常脆弱.