2

我不确定我做错了什么,或者它是 PHPUnit 和模拟对象的错误。基本上我正在尝试测试是否在触发$Model->doSomething()时被调用。$Model->start()

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

完整代码如下。任何帮助将不胜感激,这让我发疯。

<?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.
4

2 回答 2

3

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

function testDoSomething( )
{
    $Model = $this->getMock('Model', array('doSomething');
    $Model->expects($this->once())->method('doSomething');
    $Model->start();
}
于 2012-08-26T20:26:33.153 回答
0

只是为了解释为什么大卫哈克尼斯的答案有效,如果你没有指定 $methods 参数,getMock那么类中的所有函数都会被模拟。顺便说一句,您可以通过以下方式确认:

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

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

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

于 2012-08-27T23:48:24.860 回答