PHPUnitを使用してモッククラスを作成し、そのクラス名を使用しての新しいインスタンスを作成する方法はありますか?
2つのメソッドを定義するインターフェースがあります。何かのようなもの:
interface FooInterface {
function getA();
function getB();
}
次に、クラス名を受け入れ、そのクラスのインスタンスを作成し、それが期待するもののインスタンスであるかどうかを確認し(FooInterface)、そのクラスの2つのメソッドを呼び出して情報を取得する別のクラスがあります。
class FooInfo {
protected $a;
protected $b;
public function __construct($fooClass) {
$foo = new $fooClass;
if (!($foo instanceof FooInterface)) {
throw new \Exception();
}
$this->a = $foo->getA();
$this->b = $foo->getB();
}
}
オブジェクトをうまくモックする方法を知っています。問題は、このクラスはオブジェクトではなくクラス名を受け入れるため(必要に応じて、指定されたクラスのインスタンスを作成するManagerの一部です)、通常のモックオブジェクトを使用できないことです。
モックオブジェクトを作成して、そのクラス名を使用しようとしました。オブジェクトをうまく作成しているようで、私がモックアウトした機能もあるようです。ただし、後で設定したwill($ this-> returnValue('myValue'))の部分には従わないようです。
public function testConstruct()
{
$foo = $this->getMockForAbstractClass('Foo', array('getA', 'getB'));
$foo->expects($this->any())->method->('getA')->will($this->returnValue('a'));
$foo->expects($this->any())->method->('getB')->will($this->returnValue('b'));
$copyClass = get_class($foo);
$copy = new $copyClass();
// Passes
$this->assertTrue(method_exists($copy, 'getA');
// Fails, $copy->getA() returns null.
$this->assertEquals($copy->getA(), $foo->getA());
}
したがって、モックされた関数はありますが、すべてnullを返します。
何か案は?