Skip to content

Commit 38f06c2

Browse files
committed
[TASK] Reset GeneralUtility::$container in UnitTestCase::tearDown()
It could be possible that unit tests sets dependency injection container calling `GeneralUtility::setContainer()` to provide service instances or mocked service instances specific bound to that test, keeping a dirty state for following unit tests. Executing unit tests in other orders, only as a subset or for example randomized can reveal these pullation and eventualy wrong expectation for other tests. [1] This change adds a automatic cleanup to the tearDown for unit tests ensuring a clean state, because there isn't a easy way to reset that within tests without using native php reflection API. So do it in a general place. It may be possible to let the specific test setting such a container intance to fail with the recommendation to refactor the test into a functional test, but is left out for now. [1] https://review.typo3.org/c/Packages/TYPO3.CMS/+/88839 Releases: main, 8, 7
1 parent 05fe9bb commit 38f06c2

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

Classes/Core/Unit/UnitTestCase.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,18 @@ protected function tearDown(): void
136136
}
137137
}
138138

139+
// Unit tests may set GeneralUtility::setContainer() with a container instance containing mocked services,
140+
// returning test specific results. Following tests may not expect that specific outcome and thus fail when
141+
// executed in another order (for example using randomized unit tests). Not having a suitable API to reset
142+
// container instance to null we are using reflection API to reset that property in each teardown to ensure
143+
// clean state for following tests.
144+
$containerPropertyReflection = new \ReflectionProperty(GeneralUtility::class, 'container');
145+
if ($containerPropertyReflection->getValue(null) !== null) {
146+
// Reset container instances set with `GeneralUtility::setContainer()`.
147+
$containerPropertyReflection->setValue(null, null);
148+
// @todo Should we fail the test recommending to transform the test to an functional test ?
149+
}
150+
139151
// Delete registered test files and directories
140152
foreach ($this->testFilesToDelete as $absoluteFileName) {
141153
$absoluteFileName = GeneralUtility::fixWindowsFilePath(PathUtility::getCanonicalPath($absoluteFileName));

0 commit comments

Comments
 (0)