0

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.

1 Answer 1

0
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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.