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

PHPUnit 10如何为同一方法的连续调用指定不同参数

在PHPUnit 10中验证同一方法的多次不同参数调用

针对你遇到的场景——需要验证同一方法多次调用时的不同参数,PHPUnit 10提供了两种直接的解决方案:

方案一:使用withConsecutive()批量指定参数组合

这是最简洁的方式,配合exactly()指定调用次数,一次性定义所有调用的参数:

$mockedQuery->expects($this->exactly(4))
    ->method('where')
    ->withConsecutive(
        ['one', $id],
        ['two', "LIKE %{$name}%"],
        ['three', false],
        ['four', true]
    )
    ->willReturn($mockedQuery);

withConsecutive()接收的数组列表,每个子数组对应一次调用的参数,顺序必须和实际调用顺序完全一致。

方案二:使用at()单独验证每一次调用

如果需要单独针对某几次调用做验证,或者需要更精细的控制,可以用at()指定调用的索引(索引从0开始):

// 验证第1次调用(索引0)
$mockedQuery->expects($this->at(0))
    ->method('where')
    ->with('one', $id)
    ->willReturn($mockedQuery);

// 验证第2次调用(索引1)
$mockedQuery->expects($this->at(1))
    ->method('where')
    ->with('two', "LIKE %{$name}%")
    ->willReturn($mockedQuery);

// 验证第3次调用(索引2)
$mockedQuery->expects($this->at(2))
    ->method('where')
    ->with('three', false)
    ->willReturn($mockedQuery);

// 验证第4次调用(索引3)
$mockedQuery->expects($this->at(3))
    ->method('where')
    ->with('four', true)
    ->willReturn($mockedQuery);

注意:使用at()时必须保证实际调用的顺序和测试中指定的索引完全匹配,否则测试会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:49:56