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

如何在PHPUnit 11.5.6中断言可变参数函数被传入恰好指定数量参数

PHPUnit 11.5.6 断言可变参数方法的参数个数问题

问题场景

给定包含可变参数bar方法的Foo类:

class Foo
{
    public function bar(int ...$params): void {}
}

测试中MockFoo实例后,使用以下代码断言bar方法被调用时传入1和2:

public function testIsCalledWithTwoParameters()
{
    $mock = $this->createMock(Foo::class);

    $mock->expects($this->once())
         ->method('bar')
         ->with(1, 2);

    $mock->bar(1, 2);
}

但当调用改为$mock->bar(1, 2, 3);时,测试不会触发断言错误——这是因为PHPUnit 11.x版本对可变参数的处理逻辑与旧版本不同:旧版本会将可变参数打包为单个数组传入断言回调,而11.x版本会直接展开可变参数为独立的参数项,导致->with(1, 2)仅验证前两个参数匹配,不会检查是否存在额外参数。

解决方案

要断言bar方法被调用时恰好传入2个参数,需使用$this->callback()自定义断言逻辑,同时检查参数数量和参数值:

public function testIsCalledWithTwoParameters()
{
    $mock = $this->createMock(Foo::class);

    $mock->expects($this->once())
         ->method('bar')
         ->with(
             $this->callback(function (...$args) {
                 // 验证参数个数为2,且前两个参数值分别为1和2
                 return count($args) === 2 && $args[0] === 1 && $args[1] === 2;
             })
         );

    // 正常调用:测试通过
    $mock->bar(1, 2);
    // 传入3个参数:触发断言失败
    // $mock->bar(1, 2, 3);
}

如果仅需限制参数个数、不关心具体值,可简化回调逻辑:

->with(
    $this->callback(function (...$args) {
        return count($args) === 2;
    })
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:58:19