-
Notifications
You must be signed in to change notification settings - Fork 40
Tutorial 7. Adding A New Random Generator
Osman Shoukry edited this page Jan 10, 2016
·
4 revisions
On occasion, you will have a class or need to randomly generate a class for testing but its construction requires special parameters. For example, if you have an Age class representing a person's age, you may have a single constructor that takes a positive int.
OpenPojo's random default constructor will send a random int without regards for this constraint, which may throw an error. The proper work around for this is to register a RandomGenerator for Age.
public class AgeRandomGenerator implements RandomGenerator {
private static final Class<?>[] TYPES = = new Class<?>[] { Age.class };
private static final Random RANDOM = new Random(System.currentTimeMillis());
// Set your upper bound for how old someone can be.
private static final int MAX_AGE = 130;
public Object doGenerate(Class<?> type) {
return new Age(RANDOM.nextInt(MAX_AGE);
}
public Collection<Class<?>> getTypes() {
return Arrays.asList(TYPES);
}
}
public class SomeTest {
@BeforeClass
public static void onlyOnce() {
RandomFactory.addRandomGenerator(new AgeRandomGenerator());
}
// The rest of your test code goes here.
// [...]
}