Last active
April 1, 2025 14:22
-
-
Save bizley/d4bd39d0c4a1b4106c56845ff0c07068 to your computer and use it in GitHub Desktop.
PHPUnit 10 withConsecutive() replacement (using with())
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Tests\Unit; | |
use PHPUnit\Framework\Constraint\Constraint; | |
class ConsecutiveCalls extends Constraint | |
{ | |
/** | |
* @var array<mixed> | |
*/ | |
private array $stack; | |
private int $call = 0; | |
public function __construct(mixed ...$args) | |
{ | |
$this->stack = $args; | |
} | |
protected function matches(mixed $other): bool | |
{ | |
$this->call++; | |
$value = \array_shift($this->stack); | |
if ($value instanceof Constraint) { | |
return $value->evaluate($other, '', true); // @phpstan-ignore-line | |
} | |
return $value === $other; | |
} | |
public function toString(): string | |
{ | |
return \sprintf('was called the #%d time', $this->call); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Tests\Unit; | |
use PHPUnit\Framework\TestCase; | |
class BearerTest extends TestCase | |
{ | |
public function testConsecutiveArguments(): void | |
{ | |
// expects arguments: | |
// 'abc' and 8 on first call | |
// 'def' and 2 on second call | |
$this->createMock(Mocked::class) | |
->expects(self::exactly(2)) | |
->method('name') | |
->with( | |
new ConsecutiveCalls('abc', 'def'), | |
new ConsecutiveCalls(8, 2), | |
) | |
->willReturn(1); | |
// expects arguments: | |
// 'abc' and 8 on first call | |
// 'def' and 8 on second call | |
$this->createMock(Mocked::class) | |
->expects(self::exactly(2)) | |
->method('name') | |
->with( | |
new ConsecutiveCalls('abc', 'def'), | |
8, | |
) | |
->willReturn(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment