Mocking/Stubbing an Object of a class that implements arrayaccess in PHPUnit
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.