diff --git a/core/tests/Drupal/TestTools/PhpUnitCompatibility/ClassWriter.php b/core/tests/Drupal/TestTools/PhpUnitCompatibility/ClassWriter.php
index 5870de06ab8d76efe8377223a5af3675fdf6273c..4b3f9cf92632b9bca96b9f0700704df9f506512a 100644
--- a/core/tests/Drupal/TestTools/PhpUnitCompatibility/ClassWriter.php
+++ b/core/tests/Drupal/TestTools/PhpUnitCompatibility/ClassWriter.php
@@ -104,8 +104,8 @@ private static function flushAlteredCodeToFile(string $file_name, string $altere
     // Only write when necessary.
     if (!file_exists($full_path) || md5_file($full_path) !== md5($altered_code)) {
       // Create directory when necessary.
-      if (!file_exists($directory)) {
-        mkdir($directory, 0777, TRUE);
+      if (!is_dir($directory) && !@mkdir($directory, 0777, TRUE) && !is_dir($directory)) {
+        throw new \RuntimeException('Unable to create directory: ' . $directory);
       }
       file_put_contents($full_path, $altered_code);
     }