假设我有模板方法设计模式实现的代码。我想在我的模板方法中测试方法调用的序列和计数。我尝试使用PHPUnit模拟。我的源代码如下所示:
class Foo {
public function __construct() {}
public function foobar() {
$this->foo();
$this->bar();
}
protected function foo() {}
protected function bar() {}
}
class FooTest extends PHPUnit_Framework_TestCase {
public function testFoo() {
$fooMock = $this->getMock('Foo', array('foo', 'bar'));
$fooMock->foobar();
$fooMock->expects($this->once())->method('foo');
$fooMock->expects($this->once())->method('bar');
}
}
结果我有这样的错误:
PHPUnit_Framework_ExpectationFailedException :
Expectation failed for method name is equal to <string:foo> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
是否可以使用模拟对象在这种情况下计算方法调用?
答案 0 :(得分:0)
这只是我的愚蠢错误。错误的模拟对象创建序列:
// ...
public function testFoo() {
$fooMock = $this->getMock('Foo', array('foo', 'bar'));
$fooMock->expects($this->once())->method('foo'); // (!) immediately after
$fooMock->expects($this->once())->method('bar'); // mock object instantiation
$fooMock->foobar();
}