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

问题描述 投票:1回答:1

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

functionInMock未执行(确定,预期结果:无错误):

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

functionInMock被执行1次(OK,预期结果:无错误):

$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')
;

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

php phpunit
1个回答
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.
© www.soinside.com 2019 - 2024. All rights reserved.