diff --git a/src/TestCase.php b/src/TestCase.php index 79f6bfa..314a407 100644 --- a/src/TestCase.php +++ b/src/TestCase.php @@ -202,23 +202,32 @@ protected function getTestAttributes(string $attribute, string $method = null): protected function setUpTraits(): void { - $ref = new \ReflectionClass(static::class); - - foreach ($ref->getTraits() as $trait) { - if (\method_exists($this, $method = 'setUp' . $trait->getShortName())) { - $this->{$method}(); - } - } + $this->runTraitSetUpOrTearDown('setUp'); } protected function tearDownTraits(): void + { + $this->runTraitSetUpOrTearDown('tearDown'); + } + + private function runTraitSetUpOrTearDown(string $method): void { $ref = new \ReflectionClass(static::class); foreach ($ref->getTraits() as $trait) { - if (\method_exists($this, $method = 'tearDown' . $trait->getShortName())) { - $this->{$method}(); + if (\method_exists($this, $name = $method . $trait->getShortName())) { + $this->{$name}(); + } + } + + while($parent = $ref->getParentClass()) { + foreach ($parent->getTraits() as $trait) { + if (\method_exists($this, $name = $method . $trait->getShortName())) { + $this->{$name}(); + } } + + $ref = $parent; } } } diff --git a/tests/src/TestCase/Fixture/OtherParentClass.php b/tests/src/TestCase/Fixture/OtherParentClass.php new file mode 100644 index 0000000..51f5bb6 --- /dev/null +++ b/tests/src/TestCase/Fixture/OtherParentClass.php @@ -0,0 +1,9 @@ +setUp(); } + /** + * @doesNotPerformAssertions + */ #[DoesNotPerformAssertions] public function testItDoesNotThrowWhenCallingTearDown(): void { @@ -64,4 +72,24 @@ public function testTraitWithSetUpAndTearDownMethods(): void $this->assertTrue($testCase->calledSetUp); $this->assertTrue($testCase->calledTearDown); } + + public function testTraitWithSetUpAndTearDownMethodsInParentClass(): void + { + $testCase = new WithMethodsInParent('foo'); + $testCase->setUp(); + $testCase->tearDown(); + + $this->assertTrue($testCase->calledSetUp); + $this->assertTrue($testCase->calledTearDown); + } + + public function testTraitWithSetUpAndTearDownMethodsInNestedParentClass(): void + { + $testCase = new WithMethodsInNestedParent('foo'); + $testCase->setUp(); + $testCase->tearDown(); + + $this->assertTrue($testCase->calledSetUp); + $this->assertTrue($testCase->calledTearDown); + } }