Skip to content

Instantly share code, notes, and snippets.

@michelv
Last active March 2, 2023 15:07
Show Gist options
  • Save michelv/8218895fbaf6c325664877f4a18ca874 to your computer and use it in GitHub Desktop.
Save michelv/8218895fbaf6c325664877f4a18ca874 to your computer and use it in GitHub Desktop.
Replacement for PHPUnit's deprecated method InvocationMocker::withConsecutive

DO NOT USE THIS TRAIT, USE THIS ONE INSTEAD: sebastianbergmann/phpunit#4026 (comment)

ConsecutiveCallsTrait for PHPUnit 10+

This is a trait that you can use in your PHPUnit tests, to replace the use of ->withConsecutive() before upgrading to PHPUnit 10, while preserving the functionality.

Usage

  • save the file ConsecutiveCallsTrait wherever you want in your codebase
  • add your own namespace to the file
  • use the trait in your test files
  • replace all uses of ->withConsecutive( ... ) by ->with($this->consecutiveCalls( ... ))
  • relax and eventually upgrade to PHPUnit 10
<?php
declare(strict_types=1);
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\Constraint;
/**
* This is a replacement for InvocationMocker::withConsecutive() which is
* deprecated and will not be available in PHPUnit 10.
*/
trait ConsecutiveCallsTrait
{
/**
* @param array<mixed|Constraint> $expectedArgsList
* @return Callback<mixed|Constraint>
*/
protected static function consecutiveCalls(array ...$expectedArgsList): Callback
{
return Assert::callback(function (mixed ...$args) use ($expectedArgsList): bool {
static $invocationCount = 0;
$expectedArgs = $expectedArgsList[$invocationCount++];
if (count($args) > count($expectedArgs)) {
return false;
}
foreach ($args as $key => $arg) {
if ($expectedArgs[$key] instanceof Constraint) {
Assert::assertThat($arg, $expectedArgs[$key]);
} else {
Assert::assertEquals($expectedArgs[$key], $arg);
}
}
return true;
});
}
}
@DavideBicego
Copy link

Unfortunately this asserts only on the first argument of each invocation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment