PHPUnit - 何时被调用计数计为“已执行”/“调用”的方法?

时间:2012-09-20 07:02:55

标签: unit-testing phpunit invocation

我的PHPUnit测试出了问题。我有一个方法:

public function bla() 
{
    $this->blub();
}

$ _ testObject是Foo的模拟实例,如下所示:

public function setUp()
{
    $this->_testObject = $this->getMockBuilder('Foo')
                              ->setMethods(array('blub'))
                              ->getMock();
}

我的测试方法如下:

/**
 * @test
 * @covers Foo::bla
 */
public function shouldCallBlubOnce() 
{
    $this->_testObject->expects($this->once())
                      ->method('blub');

    //forgot this one :D
    $this->_testObject->bla();
}

此测试的结果提供:

PHPUnit_Framework_ExpectationFailedException : 
Expectation failed for method name is equal to <string:blub> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

提前致谢。 :)

1 个答案:

答案 0 :(得分:0)

以下测试使用PHPUnit 3.6.12在我的系统上传递。

class Foo {
    function bla() {
        $this->blub();
    }

    function blub() {
        echo 'blub';
    }
}

class FooTest extends PHPUnit_Framework_TestCase {
    function setUp() {
        $this->_testObject = $this->getMockBuilder('Foo')
                                  ->setMethods(array('blub'))
                                  ->getMock();
    }

    /**
     * @test
     * @covers Foo::bla
     */
    public function shouldCallBlubOnce() 
    {
        $this->_testObject->expects($this->once())
                          ->method('blub');
        $this->_testObject->bla();
    }
}

运行测试会产生以下结果:

PHPUnit 3.6.12 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 12.50Mb

OK (1 test, 1 assertion)