【问题标题】:Testing template method design pattern implementation with PHPUnit Mock Objects使用 PHPUnit 模拟对象测试模板方法设计模式实现
【发布时间】:2014-02-17 15:10:09
【问题描述】:

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

是否可以使用模拟对象在这种情况下计算方法调用?

【问题讨论】:

    标签: php unit-testing mocking phpunit template-method-pattern


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-28
      • 2017-02-27
      • 2013-09-12
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      相关资源
      最近更新 更多