DrupalTestCaseTrait.php
Same filename and directory in other branches
Namespace
Drupal\TestsFile
-
core/
tests/ Drupal/ Tests/ DrupalTestCaseTrait.php
View source
<?php
// @todo remove the ignore directive once PHPCS will support hooked properties.
// phpcs:ignoreFile
declare (strict_types=1);
namespace Drupal\Tests;
use Drupal\TestTools\ErrorHandler\BootstrapErrorHandler;
use Drupal\TestTools\Extension\DeprecationBridge\DeprecationHandler;
use Drupal\TestTools\Extension\Dump\DebugDump;
use PHPUnit\Framework\Attributes\After;
use PHPUnit\Framework\Attributes\BeforeClass;
use Symfony\Component\VarDumper\VarDumper;
/**
* Provides methods common across all Drupal abstract base test classes.
*
* This trait is meant to be used only by test classes.
*/
trait DrupalTestCaseTrait {
/**
* The Drupal root directory.
*/
protected string $root {
get {
if (!isset($this->root)) {
$this->root = static::getDrupalRoot();
}
return $this->root;
}
}
/**
* Returns the Drupal root directory.
*
* @return string
* The Drupal root directory.
*/
protected static function getDrupalRoot() : string {
return dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
}
/**
* Registers the dumper CLI handler when the DebugDump extension is enabled.
*/
public static function setDebugDumpHandler() : void {
if (DebugDump::isEnabled()) {
VarDumper::setHandler(DebugDump::class . '::cliHandler');
}
}
/**
* Checks the test error handler after test execution.
*/
public function checkErrorHandlerOnTearDown() : void {
// We expect that the current error handler is the one set during the
// PHPUnit bootstrap. If not, the error handler was changed during the test
// execution but not properly restored during ::tearDown().
if (DeprecationHandler::isEnabled() && !get_error_handler() instanceof BootstrapErrorHandler) {
throw new \RuntimeException(sprintf('%s registered its own error handler without restoring the previous one before or during tear down. This can cause unpredictable test results. Ensure the test cleans up after itself.', $this->name()));
}
}
}
Traits
| Title | Deprecated | Summary |
|---|---|---|
| DrupalTestCaseTrait | Provides methods common across all Drupal abstract base test classes. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.