Methods for generating random data for testing

Very often for testing purpose huge amounts of data is required. Instead of using dictionary words it is better to generate random words and numbers. Here is a class with methods that generate random random String data.

import java.util.Random;

public class RandomStringGeneratorUtil {

private final static char[] alphabets = {
'a' , 'b' , 'c' , 'd' , 'e' , 'f' ,
'g' , 'h' , 'i' , 'j' , 'k' , 'l' ,
'm' , 'n' , 'o' , 'p' , 'q' , 'r' ,
's' , 't' , 'u' , 'v' , 'w' , 'x' ,
'y' , 'z'
};

/**
* Use this method to generate strings of specified length.
*
* @param rng
* @param chars
*/
public static void randomString(Random rng, char[] chars) {
for(int i=0; i < chars.length; i++) {
chars[i] = alphabets[rng.nextInt(alphabets.length)];
}
}

/**
* This is a fast method to generate random numbers as string.
*
* @param rng
* @return
*/
public static String randomString(Random rng) {
return Integer.toString(Math.abs(rng.nextInt()));
}

/**
* This generates words in a particular order.
* eg. a,b,c, .... y,z,aa,bb,...,aaa,bbb,....
*
* @param sequentialWord
*/
public static void sequentialWord(String[] sequentialWord) {

for(int i = 0; i < sequentialWord.length; i++) {
StringBuilder word = new StringBuilder();
if(i >= alphabets.length) {
char c = alphabets[i % alphabets.length];
word.append(c);
for(int j = 0; j < i/alphabets.length; j++)
word.append(c);
} else {
word.append(alphabets[i]);
}
sequentialWord[i] = word.toString();
}
}

public static void main(String args[]) {
char[] chars = new char[10];
Random rng = new Random();
int count = 100;
for(int i=0; i< count; i++) {
randomString(rng, chars);
}

for(int i=0; i< count; i++) {
randomString(rng);
}

String[] sequentialWord = new String[100];
sequentialWord(sequentialWord);
}
}

Comments

Popular posts from this blog

java.util.logging - Bad level value for property: org.openqa.level

Solaris : Send mail with attachment

Suppressing JExcel warnings