From a4723ec01c8165ef9f6a28c56d3c71147193f326 Mon Sep 17 00:00:00 2001 From: Jamie York Date: Thu, 26 May 2022 14:23:25 +0100 Subject: [PATCH] Allow bootable test traits to teardown. (#42521) --- .../Foundation/Testing/TestCase.php | 8 ++++--- tests/Foundation/Testing/BootTraitsTest.php | 21 ++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Illuminate/Foundation/Testing/TestCase.php b/src/Illuminate/Foundation/Testing/TestCase.php index 34aa06582d4d..ea2e269cfc79 100644 --- a/src/Illuminate/Foundation/Testing/TestCase.php +++ b/src/Illuminate/Foundation/Testing/TestCase.php @@ -144,11 +144,13 @@ protected function setUpTraits() } foreach ($uses as $trait) { - $method = 'setUp'.class_basename($trait); - - if (method_exists($this, $method)) { + if (method_exists($this, $method = 'setUp'.class_basename($trait))) { $this->{$method}(); } + + if (method_exists($this, $method = 'tearDown'.class_basename($trait))) { + $this->beforeApplicationDestroyed(fn () => $this->{$method}()); + } } return $uses; diff --git a/tests/Foundation/Testing/BootTraitsTest.php b/tests/Foundation/Testing/BootTraitsTest.php index b26d66481152..0f25ffa23b93 100644 --- a/tests/Foundation/Testing/BootTraitsTest.php +++ b/tests/Foundation/Testing/BootTraitsTest.php @@ -8,11 +8,17 @@ trait TestTrait { - public $booted = false; + public $setUp = false; + public $tearDown = false; public function setUpTestTrait() { - $this->booted = true; + $this->setUp = true; + } + + public function tearDownTestTrait() + { + $this->tearDown = true; } } @@ -24,13 +30,18 @@ class TestCaseWithTrait extends FoundationTestCase class BootTraitsTest extends TestCase { - public function testSetUpTraitsWithBootMethod() + public function testSetUpAndTearDownTraits() { $testCase = new TestCaseWithTrait; - $method = new \ReflectionMethod(get_class($testCase), 'setUpTraits'); + $method = new \ReflectionMethod($testCase, 'setUpTraits'); + tap($method)->setAccessible(true)->invoke($testCase); + + $this->assertTrue($testCase->setUp); + + $method = new \ReflectionMethod($testCase, 'callBeforeApplicationDestroyedCallbacks'); tap($method)->setAccessible(true)->invoke($testCase); - $this->assertTrue($testCase->booted); + $this->assertTrue($testCase->tearDown); } }