From f0d32defd853647f157f296d12ec648679c4f296 Mon Sep 17 00:00:00 2001 From: David Maicher Date: Tue, 5 Dec 2023 17:01:16 +0100 Subject: [PATCH] fix rolling back transaction for errored tests --- .../PHPUnit/PHPUnitExtension.php | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/DAMA/DoctrineTestBundle/PHPUnit/PHPUnitExtension.php b/src/DAMA/DoctrineTestBundle/PHPUnit/PHPUnitExtension.php index e4a2dac..d34ac52 100644 --- a/src/DAMA/DoctrineTestBundle/PHPUnit/PHPUnitExtension.php +++ b/src/DAMA/DoctrineTestBundle/PHPUnit/PHPUnitExtension.php @@ -3,6 +3,8 @@ namespace DAMA\DoctrineTestBundle\PHPUnit; use DAMA\DoctrineTestBundle\Doctrine\DBAL\StaticDriver; +use PHPUnit\Event\Test\Errored; +use PHPUnit\Event\Test\ErroredSubscriber; use PHPUnit\Event\Test\Finished as TestFinishedEvent; use PHPUnit\Event\Test\FinishedSubscriber as TestFinishedSubscriber; use PHPUnit\Event\Test\PreparationStarted as TestStartedEvent; @@ -28,7 +30,17 @@ */ class PHPUnitExtension implements Extension { - public static $rolledBack = false; + public static $transactionStarted = false; + + public static function rollBack(): void + { + if (!self::$transactionStarted) { + return; + } + + StaticDriver::rollBack(); + self::$transactionStarted = false; + } public function bootstrap(Configuration $configuration, Facade $facade, ParameterCollection $parameters): void { @@ -42,8 +54,8 @@ public function notify(TestRunnerStartedEvent $event): void $facade->registerSubscriber(new class() implements TestStartedSubscriber { public function notify(TestStartedEvent $event): void { - PHPUnitExtension::$rolledBack = false; StaticDriver::beginTransaction(); + PHPUnitExtension::$transactionStarted = true; } }); @@ -52,18 +64,22 @@ public function notify(Skipped $event): void { // this is a workaround to allow skipping tests within the setUp() method // as for those cases there is no Finished event - PHPUnitExtension::$rolledBack = true; - StaticDriver::rollBack(); + PHPUnitExtension::rollBack(); } }); $facade->registerSubscriber(new class() implements TestFinishedSubscriber { public function notify(TestFinishedEvent $event): void { - // we only roll back if we did not already do it in the SkippedSubscriber - if (!PHPUnitExtension::$rolledBack) { - StaticDriver::rollBack(); - } + PHPUnitExtension::rollBack(); + } + }); + + $facade->registerSubscriber(new class() implements ErroredSubscriber { + public function notify(Errored $event): void + { + // needed as for errored tests the "Finished" event is not triggered + PHPUnitExtension::rollBack(); } });