Skip to content

Callback constraint does not handle variadic arguments correctly when used for mock object expectations #5891

@xopino

Description

@xopino
Q A
PHPUnit version 9.6.13
PHP version 8.2
Installation Method Composer

Summary

I need to assert the number of elements being passed as an argument on a mocked method for a mocked service.
The argument being passed is an spread operator, and I experience a weird behaviour when unpacking the array.
It always unpack the array as 1 element even the argument passed is an array with multiple elements, it just returns one.

Current behavior

Unpacking spread operator when trying to assert the expected arguments being passed to a mocked method returns always 1 element of the array being passed instead of the full array.

How to reproduce

//Class being mocked:

interface EventBusInterface
{
    public function publish(DomainEvent ...$events): void;
}

//Class being used:

$this->eventBus->publish(...$events);

//Test:

$eventBusMock = $this->createMock(EventBusInterface::class);
$eventBusMock
    ->expects($this->once())
    ->method('publish')
    ->with(self::callback(function (...$receivedEvents) : bool {

        $this->assertCount($expectedNumber, $receivedEvents); //Received events is always 1 element...
        return true;
    }));

Expected behavior

Inside the self::callback function, when counting the number of elements inside of the array passed as spread operator should return the actual number of elements.

For example:

$events = [$event1, $event2];
$this->eventBus->publish(...$events);
$eventBusMock = $this->createMock(EventBusInterface::class);
$eventBusMock
    ->expects($this->once())
    ->method('publish')
    ->with(self::callback(function (...$receivedEvents) : bool {

        $this->assertCount(2, $receivedEvents); //Should return true, as $receivedEvents should contain 2 events.
        return true;
    }));

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature/test-doublesTest Stubs and Mock Objectstype/bugSomething is brokenversion/10Something affects PHPUnit 10version/11Something affects PHPUnit 11

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions