Question

Suppose I have code with template method design pattern implementation. And I want to test sequence and counts of methods calls in my template method. I try to use PHPUnit mocks. My source code looks like this:

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

As a result I have such error:

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.

Is it possible to count method calls in such scenario using mock objects?

Was it helpful?

Solution

It is just my stupid mistake. Wrong mock object creation sequence:

// ...

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();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top