Skip to content

Instantly share code, notes, and snippets.

@kunicmarko20
Created February 7, 2020 17:11
Show Gist options
  • Save kunicmarko20/f80f55d9a226ae26c85ae1d45d96217d to your computer and use it in GitHub Desktop.
Save kunicmarko20/f80f55d9a226ae26c85ae1d45d96217d to your computer and use it in GitHub Desktop.
Example of annotation reader in phpunit hooks
<?php
namespace PHPUnitE2EExtension\Annotation;
/**
* @Annotation
* @Target("Class")
*/
final class E2E
{
}
<?php
declare(strict_types=1);
namespace PHPUnitE2EExtension;
use PHPUnit\Runner\BeforeTestHook;
use PHPUnit\Runner\AfterLastTestHook;
use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnitE2EExtension\Annotation\E2E;
final class MyExtension implements BeforeTestHook, AfterTestHook
{
/**
* @var AnnotationReader
*/
private static $annotationReader;
private function annotationReader()
{
if (self::$annotationReader === null) {
AnnotationRegistry::registerLoader('class_exists');
self::$annotationReader = new AnnotationReader();
}
return self::$annotationReader;
}
public function executeBeforeTest(string $test): void
{
if (!$this->isE2Etest()) {
return;
}
// do your logic
}
private function isE2Etest(string $test): bool
{
[$class] = \explode('::', $test);
return $this->annotationReader()->getClassAnnotation(
new \ReflectionClass($class),
E2E::class
) !== null;
}
public function executeAfterTest(string $test, float $time): void
{
if (!$this->isE2Etest()) {
return;
}
// do your logic
}
}
<?php
declare(strict_types=1);
namespace Tests;
use PHPUnitE2EExtension\Annotation\E2E;
use PHPUnit\Framework\TestCase;
/**
* @E2E
*/
final class ExpirationDateHandlerTest extends TestCase
{
}
<extensions>
<extension class="PHPUnitE2EExtension\MyExtension" />
</extensions>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment