PHPUnit:测试一个函数仅被调用一次

时间:2020-04-04 09:45:49

标签: php phpunit

使用PHPUnit,我想测试一个函数在Mocked Class中仅被调用一次。我测试了几种情况以确保了解excepts()

functionInMock未执行(好,预期结果:没有错误):

$myMock
    ->expects($this->never())
    ->method('functionInMock')
;

functionInMock执行了1次(好,预期结果:没有错误):

$myMock
    ->expects($this->once())
    ->method('functionInMock')
;

functionInMock执行了2次(好,预期结果:错误):

$myMock
    ->expects($this->once())
    ->method('functionInMock')
;

functionInMock执行1次:

$myMock
    ->expects($this->exactly(2))
    ->method('functionInMock')
;

or

$myMock
    ->expects($this->exactly(999))
    ->method('functionInMock')
;

为什么在最后一种情况下我没有错误?测试通过且未报告错误。

1 个答案:

答案 0 :(得分:0)

我不确定您为什么会有意外的行为,但是此示例可以正常工作

<?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.