PHPUnit 10 allows specifying different method parameters when calling the same method consecutively
P粉639667504
P粉639667504 2024-04-05 10:38:10
0
1
1531

I have a method that is called multiple times with different parameters as part of a larger method.

$query->where("one", $id);
$query->where("two", "LIKE %{$name}%");
$query->where("three", false);
$query->where("four", true);

I'm using PHPUnit 10 and I want to write a unit test for this specific method. I want to check if the where method is called 4 times with some specific parameters.

For example:

$mockedQuery->expects($this->exactly(4))
->method("where")
->with(
// Here I'd like to specify the list of arguments
// or perhaps a map or something
)
->willReturn($mockedQuery);

->will above doesn't work for specifying different parameters for successive calls to the same method (or at least I couldn't get it to work).

I've tried using the documentation but don't know what exactly to search for so it's hard to find.

P粉639667504
P粉639667504

reply all(1)
P粉798343415

I'll answer my own question because I had to do some digging.

With PHPUnit 10, the method withConsecutive (that's what I'm looking for, I just didn't know it was called this) has been removed. No official replacement exists.

This issue was asked on the PHPUnit repository

The solution I used is

$matcher = $this->exactly(2);
$this->mock
    ->expects($matcher)
    ->method('get')
    ->willReturnCallback(function (string $param) use ($matcher) {
                match ($matcher->numberOfInvocations()) {
                    1 => $this->assertEquals($param, 'someValue'),
                    2 => $this->assertEquals($param, 'someOtherValue'),
                };
            })
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template