有没有好的方法可以使用PHPUnit模拟抽象类中的具体方法?
目前我找到的解决方案有:
- expects() ->will() 可以很好地用于抽象方法。 - 但是对于具体方法,它不起作用。原始方法仍会运行。 - 使用MockBuilder并将所有抽象方法和具体方法传递给setMethods()可以解决问题,但需要指定所有抽象方法,这样测试就变得脆弱且过度冗长。 - MockBuilder :: getMockForAbstractClass() 忽略setMethod()。
这里是一些单元测试,说明了上述要点:
目前我找到的解决方案有:
- expects() ->will() 可以很好地用于抽象方法。 - 但是对于具体方法,它不起作用。原始方法仍会运行。 - 使用MockBuilder并将所有抽象方法和具体方法传递给setMethods()可以解决问题,但需要指定所有抽象方法,这样测试就变得脆弱且过度冗长。 - MockBuilder :: getMockForAbstractClass() 忽略setMethod()。
这里是一些单元测试,说明了上述要点:
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
}
}