Skip to content

Instantly share code, notes, and snippets.

@bizley
Last active May 14, 2024 06:25
Show Gist options
  • Save bizley/d4bd39d0c4a1b4106c56845ff0c07068 to your computer and use it in GitHub Desktop.
Save bizley/d4bd39d0c4a1b4106c56845ff0c07068 to your computer and use it in GitHub Desktop.
PHPUnit 10 withConsecutive() replacement (using with())
<?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);
}
}
<?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')
->wiith(
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')
->wiith(
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