Issue
What is the best practice for creating random strings when testing spring junit?
When writing a test with junit, I use the code below when creating a random string.
UUID.randomUUID().toString().substring(0, 20)
The disadvantage of this code is that it cannot exceed the maximum length of a UUID of 32 characters.
I have no doubt that there must be a better way than the code above.
I'm wondering what is the best practice to return a random string.
best regards!
Solution
Using Java 8 you can generate a random string of a-z characters using Random().ints(97, 123)
this works because the character a
is represented as 97
and z
is represented as 122
.
Then we can use .collect(...)
to convert the characters from random into a string.
Altogether the code looks like this:
int yourStringLength = 40;
String generatedString = new Random().ints(97, 123)
.limit(yourStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
And the resulting string would look a bit like this:
okphrralxtqywxgfnolloyiqfjlgputyzprpbwsr
If you want to also include spaces then simply start the .ints(...)
at 96 which is the ` character, and replace it with spaces once generated:
String generatedString = new Random().ints(97, 123)
.limit(yourStringLength)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
generatedString = generatedString.replaceAll("`", " ");
And the resulting string would look a bit like this:
ayowotibx sotvonazpm vjnyobdkzajfckutswu
If you want even more spaces to represent real word lengths then you can start the .ints(...)
even earlier or push out the top end, and replace the characters as required, for example for ints(96, 123)
also replace generatedString = generatedString.replaceAll("_", " ");
and the result would be like this:
hrqobe rufmcknwobzyh whaimaxgjsjg nyxcx
Answered By - sorifiend
Answer Checked By - Pedro (JavaFixing Volunteer)