diff --git a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
index cb4b7c5..6b0e299 100644
--- a/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
+++ b/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
@@ -531,7 +531,9 @@ protected function drupalCreateRole(array $permissions, $rid = NULL, $name = NUL
     }
     // Generate a random label.
     if (!isset($name)) {
-      $name = $this->randomString(8);
+      // In the role UI role names are trimmed and random string can start or
+      // end with a space.
+      $name = trim($this->randomString(8)) . ' ';
     }
 
     // Check the all the permissions strings are valid.
