Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate number, character, strings, boolean and dates for test data using strategy design pattern.
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Random;
interface Generator<T> {
T generate();
static Generator<Boolean> generateBoolean(){
return new Generator<>() {
Random random = new Random();
@Override
public Boolean generate() {
return random.nextBoolean();
}
};
}
static Generator<Integer> generateNumber(){
return () -> new Random().nextInt(100000);
}
static Generator<Character> generateCharacter(){
return new Generator<>() {
Random random = new Random();
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
@Override
public Character generate() {
return chars[random.nextInt(chars.length)];
}
};
}
static Generator<String> generateString(){
return () -> {
char[] chars = new char[7];
Generator<Character> generator = generateCharacter();
for(int i=0; i<7; i++){
chars[i] = generator.generate();
}
return new String(chars);
};
}
static Generator<LocalDate> generateDate(){
return () -> {
// Number of seconds from 1970 Jan 1 to 2018 Dec 31 is 1546214400.
int instance = new Random().nextInt(1546214400);
return LocalDate.ofInstant(Instant.ofEpochSecond(instance), ZoneId.systemDefault());
};
}
}
class GeneratorTest{
public static void main(String[] args) {
testGenerator(Generator.generateNumber());
testGenerator(Generator.generateBoolean());
testGenerator(Generator.generateCharacter());
testGenerator(Generator.generateString());
testGenerator(Generator.generateDate());
}
private static void testGenerator(Generator<? extends Comparable> gen){
for(int i=0; i< 5;i++)
System.out.print(gen.generate()+" ");
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment