2014-02-17 78 views
0

假设我有模板方法设计模式实现的代码。我想在我的模板方法中测试方法调用的顺序和计数。我尝试使用PHPUnit模拟。我的源代码如下所示:使用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

这只是我愚蠢的错误。错误的模拟对象创建序列:

// ... 

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(); 
}