search

Home  >  Q&A  >  body text

PHPUnit 10 allows specifying different method parameters when calling the same method consecutively

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粉639667504P粉639667504308 days ago1623

reply all(1)I'll reply

  • P粉798343415

    P粉7983434152024-04-06 00:53:32

    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'),
                    };
                })

    reply
    0
  • Cancelreply