I’m using PHPUnit test doubles to mock models, libraries etc. But when I want to return an array perhaps of container objects, how best to do so. Here is what I’m currently doing:
/**
* This is just a mock of the response from http client
*/
class Container {
public $values;
public function __construct($values) {
$this->values = $values;
}
public function __get($name) {
return (isset($values[$name])) ? $values[$name] : null;
}
public function __set($name, $value) {
$values[$name] = $value;
}
}
.. then in my test* methods I may do something like:
$userMock = new Container(array('id' => 2, 'name'=>'Tom'));
$this->mock
->method('find') // called within BaseController
->with(2)
->willReturn( $userMock );
So I don’t know if I can use PHPUnit tets doubles or Mockery to create such classes, can I? It seems simpler to just do this way, is this a good approach though?
Generally, you don’t need to mock value objects (and your container objects seems like value objects) and your approach is right.
If you need to write assertions to the properties, I would consider it a code smell. Still, PHP Unit allows you to mock magic methods, so you can assert the __set calls for example, or you can just assert the end value of the property (assuming you need to assert that the properties are correctly set, if you need to assert that they are read, that’s a test smell; as you should verify the end result of the code that uses them, and not it’s exact implementation, e.g. don’t verify where it got value from, but verify what it did with that value)