我不确定我做错了什么,或者它是PHPUnit和mock对象的错误。基本上我试图测试$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.
答案 0 :(得分:3)
正如您所发现的,您需要告诉PHPUnit要模拟哪些方法。此外,我会避免为您直接从测试中调用的方法创建期望。我会像这样写上面的测试:
function testDoSomething( )
{
$Model = $this->getMock('Model', array('doSomething');
$Model->expects($this->once())->method('doSomething');
$Model->start();
}
答案 1 :(得分:0)
为了扩展为什么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();
行永远不会被运行。
因此,当您的班级中有任何需要保留的功能时,您必须明确提供所有其他功能的列表。