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 调用该方法一次,但我们预期调用两次,所以它应该失败了——但它通过了,为什么? testC没问题,没问题 testD 失败所以没问题
也许 exactly() 并没有像我预期的那样工作。我正在使用最新的 4.3.4 PhPunit。
最佳答案
尝试在 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.
希望对你有帮助
关于Phpunit,期望一个方法正好运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672977/