You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何替换PHPUnit 10中废弃的withConsecutive方法?

替代PHPUnit废弃的withConsecutive()的两种可行方案

PHPUnit 9.6将withConsecutive()标记为废弃,PHPUnit 10会彻底移除该方法。针对你提供的示例代码,以下是两种可靠的替代方案:

方案一:拆分独立的期望调用(推荐)

将原有的单次链式调用拆分为多个独立的期望定义,通过at()指定方法调用的顺序索引(从0开始),分别匹配每次调用的参数并设置返回值:

// 匹配第一次调用的参数与返回值
$this->personServiceMock->expects($this->at(0))
    ->method('prepare')
    ->with($personFirst, $employeeFirst)
    ->willReturn($personDTO);

// 匹配第二次调用的参数与返回值
$this->personServiceMock->expects($this->at(1))
    ->method('prepare')
    ->with($personSecond, $employeeSecond)
    ->willReturn($personSecondDTO);

这种方式逻辑清晰,易于阅读和维护,尤其适合方法调用次数较少的场景。

方案二:使用闭包跟踪调用顺序(保持链式风格)

如果希望保持链式调用的写法,可以通过闭包维护一个调用计数器,在callback约束中匹配对应顺序的参数:

$callIndex = 0;
// 定义所有期望的参数组合
$expectedArgsList = [
    [$personFirst, $employeeFirst],
    [$personSecond, $employeeSecond],
];

$this->personServiceMock->expects($this->exactly(2))
    ->method('prepare')
    ->with(
        // 匹配第一个参数
        $this->callback(function ($param) use (&$callIndex, $expectedArgsList) {
            $match = $param === $expectedArgsList[$callIndex][0];
            // 仅在第一个参数匹配成功后,才准备匹配下一次调用的参数
            if ($match) {
                $callIndex++;
            }
            return $match;
        }),
        // 匹配第二个参数
        $this->callback(function ($param) use ($callIndex, $expectedArgsList) {
            return $param === $expectedArgsList[$callIndex - 1][1];
        })
    )
    ->willReturnOnConsecutiveCalls($personDTO, $personSecondDTO);

这种方式适合需要保持链式调用结构的场景,但逻辑相对复杂,需要注意计数器的同步问题。

内容的提问来源于stack exchange,提问作者yAnTar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:50:27