I'm trying to implement a type of mock for PHP objects. By using the magic methods (__call, __get) to intercept method invocation and member access, I'm pretty sure I can stash away closures and substitute them in, in order to stub methods. One thing I'm having trouble wrapping my head around, though, is how to fool type hinting into believing my object is of the mocked type.
Can this be done? Use of ReflectionClass is okay, but I'd rather not rope in PHPUnit.
Consider the following (hastily-written) code:
class Thing {};
class ThingCollection {
private $things;
public function __construct () { $this->things = array(); }
public function addThing ( Thing $thing ) { $this->things[] = $thing; }
};
class Mock {
private $__obj;
private $__stubbedMethods;
public function __construct ( $obj, $args ) {
$this->__obj = new $obj(...$args);
}
public function __call ( $name, $args ) {
if ( isset( $this->__stubbedMethods ) )
return call_user_func_array( $this->stubbedMethods, $args );
return call_user_func( $this->__obj->{$name}, $args );
}
public function stub ( $name, callable $method ) {
$this->__stubbedMethods[$name] = $method;
}
};
$mock = new Mock( 'Thing', array( 21 ) );
$collection = new ThingCollection();
$collection->addThing( $mock ); // error: "must be an instance of Thing"
Aucun commentaire:
Enregistrer un commentaire