PHPUnit和Mock对象不工作


PHPUnit and Mock Objects not working

我不确定是我做错了什么,还是PHPUnit和mock对象的错误。基本上,我试图测试当$Model->start()被触发时是否调用了$Model->doSomething()

我在VirtualBox中使用Ubuntu,phpunit 1.1.1是通过pear安装的。

完整的代码如下。任何帮助都将不胜感激,这让我抓狂。

<?php
require_once 'PHPUnit/Autoload.php';
class Model
{
    function doSomething( ) {
        echo 'Hello World';
    }
    function doNothing( ) { }
    function start( ) {
        $this->doNothing();
        $this->doSomething();
    }
}
class ModelTest extends PHPUnit_Framework_TestCase
{
    function testDoSomething( )
    {
        $Model = $this->getMock('Model');
        $Model->expects($this->once())->method('start'); # This works
        $Model->expects($this->once())->method('doSomething'); # This does not work
        $Model->start();
    }
}
?>

PHPUnit的输出:

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

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

正如您所发现的,您需要告诉PHPUnit要模拟哪些方法。此外,我会避免对您直接从测试中调用的方法产生期望。我会这样写上面的测试:

function testDoSomething( )
{
    $Model = $this->getMock('Model', array('doSomething');
    $Model->expects($this->once())->method('doSomething');
    $Model->start();
}

为了进一步解释David Harkness的答案有效的原因,如果您没有为getMock指定$methods参数,则类中的所有函数都将被模拟。顺便说一句,你可以用来确认这一点

class ModelTest extends PHPUnit_Framework_TestCase
{
    function testDoSomething( )
    {
        $obj = $this->getMock('Model');
        echo new ReflectionClass(get_class($obj));
        ...
    }
}

那么,为什么它会失败呢?因为你的start()函数也被嘲笑了!也就是说,你给出的函数体已经被替换了,所以你的$this->doSomething();行永远不会运行。

因此,当类中有任何函数需要保留时,必须显式给出所有其他函数的列表。