Mocking/Stubbing an Object of a class that implements arrayaccess in PHPUnit

て烟熏妆下的殇ゞ 提交于 2019-12-03 13:54:57

问题


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

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

class Config implements arrayaccess{...}

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

Thanks in advance!


回答1:


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

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

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



来源:https://stackoverflow.com/questions/10607173/mocking-stubbing-an-object-of-a-class-that-implements-arrayaccess-in-phpunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!