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

Here is the class constructor, 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 into php:

 class Config implements arrayaccess{...} 

How do I make fun / mute a Config object? What should i use and why?

Thanks in advance!

+8
php phpunit arrayaccess
source share
1 answer

If you can easily create an instance of Config from an array, this will be my preference. Although you want to test your units in isolation where possible, simple employees like Config should be safe enough to use in the test. The code for setting it up will probably be easier to read and write (less error prone) than the equivalent layout.

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

At the same time, you mock the object that implements ArrayAccess in the same way as 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 access order, but you will make the test very fragile.

+15
source share

All Articles