class TestMe
{
public function method() { }
}
试验:
class TestTest extends PHPUnit_Framework_TestCase
{
public function testA()
{
$stub = $this->getMock ('TestMe');
$stub->expects ($this->exactly(2))->method('method');
}
public function testB()
{
$stub = $this->getMock ('TestMe');
$stub->expects ($this->exactly(2))->method('method');
$stub->method();
}
public function testC()
{
$stub = $this->getMock ('TestMe');
$stub->expects ($this->exactly(2))->method('method');
$stub->method();
$stub->method();
}
public function testD()
{
$stub = $this->getMock ('TestMe');
$stub->expects ($this->exactly(2))->method('method');
$stub->method();
$stub->method();
$stub->method();
}
}
testA,testB,testC通过,testD失败,这很奇怪。
testA甚至没有调用该方法,所以它应该失败 - 但它过去了,为什么?
testB调用方法ONCE,但是我们预计TWICE应该失败 - 但它过去了,为什么?
testC没问题,没问题
testD失败所以没关系,没问题
也许完全()并不完全符合我的预期。我使用最新的4.3.4 PhPunit。
答案 0 :(得分:5)
尝试在getMock
来电中添加您要模拟的方法名称。
为获得预期结果,我将测试类修改为:
class TestTest extends \PHPUnit_Framework_TestCase
{
public function testA()
{
$stub = $this->getMock ('TestMe',array('method'));
$stub->expects ($this->exactly(2))->method('method');
}
public function testB()
{
$stub = $this->getMock ('TestMe',array('method'));
$stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
$stub->method();
}
public function testC()
{
$stub = $this->getMock ('TestMe',array('method'));
$stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
$stub->method();
$stub->method();
}
public function testD()
{
$stub = $this->getMock ('TestMe',array('method'));
$stub->expects ($this->exactly(2))->method('method')->withAnyParameters();
$stub->method();
$stub->method();
$stub->method();
}
}
结果是:
PHPUnit 4.3.4 by Sebastian Bergmann.
There were 3 failures:
1) Acme\DemoBundle\Tests\TestTest::testA
Expectation failed for method name is equal to <string:method> when invoked 2 time(s).
Method was expected to be called 2 times, actually called 0 times.
2) Acme\DemoBundle\Tests\TestTest::testB
Expectation failed for method name is equal to <string:method> when invoked 2 time(s).
Method was expected to be called 2 times, actually called 1 times.
3) Acme\DemoBundle\Tests\TestTest::testD
TestMe::method() was not expected to be called more than 2 times.
希望这个帮助