Skip to content

Instantly share code, notes, and snippets.

@frankiejarrett
Last active March 14, 2021 17:18
Show Gist options
  • Save frankiejarrett/e3dbe8f375316f461283e4ce8516b8bf to your computer and use it in GitHub Desktop.
Save frankiejarrett/e3dbe8f375316f461283e4ce8516b8bf to your computer and use it in GitHub Desktop.
Trait to support retry annotations on PHPUnit tests, inspired by https://blog.forma-pro.com/retry-an-erratic-test-fc4d928c57fb
<?php
namespace Tests\Traits;
use PHPUnit\Util\Test as TestUtil;
use Throwable;
trait Retry
{
/**
* @throws Throwable
*/
public function runBare(): void
{
$numberOfRetires = $this->getNumberOfRetries();
for ($i = 0; $i <= $numberOfRetires; ++$i) {
try {
parent::runBare();
} catch (Throwable $e) {
throw $e;
}
}
}
/**
* @return int
*/
protected function getNumberOfRetries()
{
$annotations = TestUtil::parseTestMethodAnnotations(static::class, $this->getName(false));
return isset($annotations['method']['retry'][0]) ? abs((int) $annotations['method']['retry'][0]) : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment