PHPUnit:测试函数是否只被调用一次
使用PHPUnit,我想测试一个函数在模拟类中只调用一次。我测试了几个案例,以确保理解PHPUnit:测试函数是否只被调用一次,php,phpunit,Php,Phpunit,使用PHPUnit,我想测试一个函数在模拟类中只调用一次。我测试了几个案例,以确保理解excepts(): functionInMock未执行(正常,预期结果:无错误): functionInMock执行1次(Ok,预期结果:无错误): functionInMock执行2次(Ok,预期结果:error): functionInMock执行一次: $myMock ->expects($this->exactly(2)) ->method('functionInMo
excepts()
:
functionInMock
未执行(正常,预期结果:无错误):
functionInMock
执行1次(Ok,预期结果:无错误):
functionInMock
执行2次(Ok,预期结果:error):
functionInMock
执行一次:
$myMock
->expects($this->exactly(2))
->method('functionInMock')
;
or
$myMock
->expects($this->exactly(999))
->method('functionInMock')
;
为什么在最后一个案例中我没有错误?测试通过,但没有报告错误。我不确定您为什么会出现意外行为,但这个示例运行良好
<?php
// Lets name it 'SampleTest.php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class SampleTest extends TestCase
{
public function testSample(): void
{
$myMock = $this
->getMockBuilder(Sample::class)
->addMethods(['functionInMock'])
->getMock();
$myMock
->expects($this->exactly(2))
->method('functionInMock');
$myMock->functionInMock();
}
}
class Sample
{
public function function2InMock(): void
{
}
}
我不知道你为什么会有意想不到的行为,但这个例子效果很好
<?php
// Lets name it 'SampleTest.php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class SampleTest extends TestCase
{
public function testSample(): void
{
$myMock = $this
->getMockBuilder(Sample::class)
->addMethods(['functionInMock'])
->getMock();
$myMock
->expects($this->exactly(2))
->method('functionInMock');
$myMock->functionInMock();
}
}
class Sample
{
public function function2InMock(): void
{
}
}
$myMock
->expects($this->exactly(2))
->method('functionInMock')
;
or
$myMock
->expects($this->exactly(999))
->method('functionInMock')
;
<?php
// Lets name it 'SampleTest.php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class SampleTest extends TestCase
{
public function testSample(): void
{
$myMock = $this
->getMockBuilder(Sample::class)
->addMethods(['functionInMock'])
->getMock();
$myMock
->expects($this->exactly(2))
->method('functionInMock');
$myMock->functionInMock();
}
}
class Sample
{
public function function2InMock(): void
{
}
}
$ phpunit SampleTest.php
PHPUnit 9.1.1 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 125 ms, Memory: 6.00 MB
There was 1 failure:
1) SampleTest::testSample
Expectation failed for method name is "functionInMock" when invoked 2 time(s).
Method was expected to be called 2 times, actually called 1 times.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.