我是Unit test的新手,正在尝试使用PHPUnit框架。
我有一个调用两个其他函数的函数:
class Dummy{
public function dummyFunction(){
$this->anotherDummyFunction();
.....
$this->yetAnotherDummyFunction();
}
public function anotherDummyFunction(){
.....
}
public function yetAnotherDummyFunction(){
.....
}
}
我希望在调用dummyFunction()时,这两个函数被调用。
这是测试类:
class TestDummyClass {
public function testDummyFunction(){
$dummyClassMock = $this->getMockBuilder('Dummy')
->setMethods( array( 'anotherDummyFunction','yetAnotherDummyFunction' ) )
->getMock();
$dummyClassMock->expects($this->once())
->method( 'anotherDummyFunction' );
$dummyClassMock->expects($this->once())
->method( 'yetAnotherDummyFunction' );
$dummyClassMock->dummyFunction();
}
}
现在我注意到,如果我以这种方式模拟Dummy类,结果是:
当调用1次时,期望方法名称等于anotherDummyFunction。该方法预计将被调用1次,实际上未被调用。
但是如果我以这种方式设置Mock对象
$dummyClassMock = $this->getMockBuilder('Dummy')
->setMethods( array( 'anotherDummyFunction' ) )
->getMock();
测试通过。最后,如果我使用setMethods(null)设置模拟对象,则测试再次失败。
看起来我可以传递只有一个元素的数组,检查是否调用了我想要检查的方法。但是我在这里看到过:https://jtreminio.com/2013/03/unit-testing-tutorial-part-5-mock-methods-and-overriding-constructors/ setMethods用于注入传递的方法的返回值,所以这不会对调用本身产生影响,除非我将dummyFunction放在setMethods中(在这种情况下,函数将返回null而不调用其他两个方法,这样测试就必须失败)。
我做错了什么吗?我已经看到了代码片段,其中setMethods()中有多个方法...为什么如果我在setMethods中放置两个方法,测试会失败?
谢谢
TestDummyClass
是从PHPUnit_Framework_TestCase
继承的吗?你使用的phpunit版本是什么?我的是4.6.9
。 - Alexander GuzPHPUnit_Framework_TestCase
,实际上其他测试都通过了。我正在使用Sublime Text和Sublime Text的PHPUnit插件进行工作。phpUnit的版本是4.6.6,但我认为我不能使用新版本,因为插件不支持。稍后我会尝试使用另一个编辑器和新版本的phpUnit。 - Manu