After seeing several topics asking about the best ways to generate random data for use in web testing, @Russ_Thomas has recommended that a topic be created that can aggregate these techniques in one convenient place. So, here goes…
Note: These were written to work alongside Katalon’s API, but be aware that all of these can be utilized outside of Katalon Studio, such as other Selenium-based tools, with the proper object translation.
Also, please note that while these are all pure Java/Selenium/Katalon implementations, there are more formalized libraries out there that are specifically designed to do this kind of thing, if you don’t mind importing and utilizing third-party software.
I will be adding solutions for commonly-encountered problems as I find them, as well as taking suggestions on how to improve them:
Returns a random character sequence of a given length from a given set of possible characters:
public static String getRandomCharSequence(int length, String possibleChars) {
StringBuilder builder = new StringBuilder();
Random rnd = new Random();
while (builder.length() < length) {
int index = (int)(rnd.nextFloat() * possibleChars.length());
builder.append(possibleChars.charAt(index));
}
return builder.toString();
}
Returns a random integer from a range of integers (lower and upper bound-inclusive):
public static int getRandomInteger(int lowerBound, int upperBound) {
return new Random().nextInt(upperBound - lowerBound + 1) + lowerBound;
}
Returns a random WebElement out of a set of WebElements defined by some TestObject, with a timeout:
public static WebElement getRandomWebElement(TestObject testObject, int timeout) {
List<WebElement> elements = WebUiCommonHelper.findWebElements(testObject, timeout);
return elements.get(new Random().nextInt(elements.size()));
}
Selects a random option for a <select>
element defined by some TestObject, with a timeout:
public static void selectRandomOption(TestObject testObject, int timeout) {
WebElement element = WebUiCommonHelper.findWebElement(testObject, timeout);
Select select = new Select(element);
select.selectByIndex(new Random().nextInt(select.getOptions() - 1));
}
Returns the current timestamp in nanoseconds (useful for appending a “random” number to other values):
public static long getCurrentTimestamp() {
return System.nanoTime();
}