PHPUnitを使用して抽象クラスで具象メソッドをモックする良い方法はありますか?phpunitを使用した抽象クラスの具体的なメソッドのモック
私がこれまでに発見したことはある:
- を期待() - >意志()は、それが具体的な方法では動作しません。抽象メソッド
- を使用して正常に動作します。代わりに元のメソッドが実行されます。
- mockbuilderを使用して、すべての抽象メソッドとsetMethods()の具体的なメソッドを提供します。ただし、すべての抽象メソッドを指定する必要があり、テストが壊れやすく冗長すぎます。
- MockBuilder :: getMockForAbstractClass()はsetMethod()を無視します。
は、ここで上記の点をexamplifyingいくつかのユニットテストです:
abstract class AbstractClass {
public function concreteMethod() {
return $this->abstractMethod();
}
public abstract function abstractMethod();
}
class AbstractClassTest extends PHPUnit_Framework_TestCase {
/**
* This works for abstract methods.
*/
public function testAbstractMethod() {
$stub = $this->getMockForAbstractClass('AbstractClass');
$stub->expects($this->any())
->method('abstractMethod')
->will($this->returnValue(2));
$this->assertSame(2, $stub->concreteMethod()); // Succeeds
}
/**
* Ideally, I would like this to work for concrete methods too.
*/
public function testConcreteMethod() {
$stub = $this->getMockForAbstractClass('AbstractClass');
$stub->expects($this->any())
->method('concreteMethod')
->will($this->returnValue(2));
$this->assertSame(2, $stub->concreteMethod()); // Fails, concreteMethod returns NULL
}
/**
* One way to mock the concrete method, is to use the mock builder,
* and set the methods to mock.
*
* The downside of doing it this way, is that all abstract methods
* must be specified in the setMethods() call. If you add a new abstract
* method, all your existing unit tests will fail.
*/
public function testConcreteMethod__mockBuilder_getMock() {
$stub = $this->getMockBuilder('AbstractClass')
->setMethods(array('concreteMethod', 'abstractMethod'))
->getMock();
$stub->expects($this->any())
->method('concreteMethod')
->will($this->returnValue(2));
$this->assertSame(2, $stub->concreteMethod()); // Succeeds
}
/**
* Similar to above, but using getMockForAbstractClass().
* Apparently, setMethods() is ignored by getMockForAbstractClass()
*/
public function testConcreteMethod__mockBuilder_getMockForAbstractClass() {
$stub = $this->getMockBuilder('AbstractClass')
->setMethods(array('concreteMethod'))
->getMockForAbstractClass();
$stub->expects($this->any())
->method('concreteMethod')
->will($this->returnValue(2));
$this->assertSame(2, $stub->concreteMethod()); // Fails, concreteMethod returns NULL
}
}
彼らは抽象的であるとして、あなたは抽象クラスをテストする必要はありません。あるいは、抽象テストケースを作成したいのですか? – hakre
抽象クラスは別のクラスの依存関係です。ですから、$ object-> concreteMethod()を使うSomeClass :: getMyCalculatedValue()をテストしたいと思います。 concreteMethod()は変更できるか、設定が難しいかもしれないので、concreteMethod()の戻り値を指定します。 – CheeseSucker