Fill primitive properties with random data automatically?
You could use PoDaM:
PodamFactory factory = new PodamFactoryImpl();
Pojo myPojo = factory.manufacturePojo(Pojo.class);
I don't know of a framework, but it's pretty simple to write one of those yourself. The complexity comes in non-simple properties, aka object associations. Something like this handles the basics and then some:
public static void randomlyPopulateFields(Object object) {
new RandomValueFieldPopulator().populate(object);
}
public static class RandomValueFieldPopulator {
public void populate(Object object) {
ReflectionUtils.doWithFields(object.getClass(), new RandomValueFieldSetterCallback(object));
}
private static class RandomValueFieldSetterCallback implements FieldCallback {
private Object targetObject;
public RandomValueFieldSetterCallback(Object targetObject) {
this.targetObject = targetObject;
}
@Override
public void doWith(Field field) throws IllegalAccessException {
Class<?> fieldType = field.getType();
if (!Modifier.isFinal(field.getModifiers())) {
Object value = generateRandomValue(fieldType, new WarnOnCantGenerateValueHandler(field));
if (!value.equals(UNGENERATED_VALUE_MARKER)) {
ReflectionUtils.makeAccessible(field);
field.set(targetObject, value);
}
}
}
}
}
public static Object generateRandomValue(Class<?> fieldType, CantGenerateValueHandler cantGenerateValueHandler) {
if (fieldType.equals(String.class)) {
return UUID.randomUUID().toString();
} else if (Date.class.isAssignableFrom(fieldType)) {
return new Date(System.currentTimeMillis() - random.nextInt(DATE_WINDOW_MILLIS));
} else if (Number.class.isAssignableFrom(fieldType)) {
return random.nextInt(Byte.MAX_VALUE) + 1;
} else if (fieldType.equals(Integer.TYPE)) {
return random.nextInt();
} else if (fieldType.equals(Long.TYPE)) {
return random.nextInt();
} else if (Enum.class.isAssignableFrom(fieldType)) {
Object[] enumValues = fieldType.getEnumConstants();
return enumValues[random.nextInt(enumValues.length)];
} else {
return cantGenerateValueHandler.handle();
}
}
Take a look at Easy Random.
It allows you to populate a Java Object graph with random data.
Hope it helps.