phpunit

How to assert variadic function has exactly n parameters with PHPUnit


PHPUnit version : 11.5.6

Given a class Foo with bar method with variadic params:

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

I mock a Foo instance in a test and want to assert bar has been called with exactly 2 parameters (not one more).

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

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

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

Problem is: changing call for $mock->bar(1, 2, 3); will not trigger an error.

NB 1: With previous versions of PHPUnit, variadic params were sent to callback as a unique array but it seems it is not longer the case in 11.5.6.


Solution

  • public function testIsCalledWithTwoParameters()
    {
        $mock = $this->createMock(Foo::class);
    
        $mock->expects($this->once())
            ->method('bar')
            ->with($this->callback(function (int ...$args): true {
                $this->assertCount(2, $args);
                $this->assertEquals(1, $args[0]);
                $this->assertEquals(2, $args[1]);
                return true;
            });
    
        // will fail
        $mock->bar(1, 2, 3);
    }