I Have used reflection and recursion here to get all fields populated in my robust object that i wanted to get tested. This is Using PODAM as well i hope somebody will find this useful.
public class Populate {
private final PodamFactory podamFactory = new PodamFactoryImpl();
private <P> P getManufacturedPojo(final Class<P> klass) {
return podamFactory.manufacturePojo(klass);
}
private Object populateAllIn(final Class targetClass) throws IllegalAccessException, InstantiationException {
final Object target = targetClass.newInstance();
//Get all fields present on the target class
final Set<Field> allFields = getAllFields(targetClass, Predicates.<Field>alwaysTrue());
//Iterate through fields
for (final Field field : allFields) {
//Set fields to be accessible even when private
field.setAccessible(true);
final Class<?> fieldType = field.getType();
if (fieldType.isEnum() && EnrichmentType.class.isAssignableFrom(fieldType)) {
//handle any enums here if you have any
}
//Check if the field is a collection
if (Collection.class.isAssignableFrom(fieldType)) {
//Get the generic type class of the collection
final Class<?> genericClass = getGenericClass(field);
//Check if the generic type of a list is abstract
if (Modifier.isAbstract(genericClass.getModifiers())) {
//You might want to use any class that extends
//Your abstract class like
final List<Object> list = new ArrayList<>();
list.add(populateAllIn(ClassExtendingAbstract.class));
field.set(target, list);
} else {
final List<Object> list = new ArrayList<>();
list.add(populateAllIn(genericClass));
field.set(target, list);
}
} else if ((isSimpleType(fieldType) || isSimplePrimitiveWrapperType(fieldType)) && !fieldType.isEnum()) {
field.set(target, getManufacturedPojo(fieldType));
} else if (!fieldType.isEnum()) {
field.set(target, populateAllIn(fieldType));
}
}
return target;
}
And some helper methods. Code might not be perfect but works :).
private Class<?> getGenericClass(final Field field) {
final ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
return (Class<?>) collectionType.getActualTypeArguments()[0];
}
private boolean isSimpleType(final Class<?> fieldType) {
return fieldType.isPrimitive()
|| fieldType.isEnum()
|| String.class.isAssignableFrom(fieldType)
|| Date.class.isAssignableFrom(fieldType);
}
private boolean isSimplePrimitiveWrapperType(final Class<?> fieldType) {
return Integer.class.isAssignableFrom(fieldType)
|| Boolean.class.isAssignableFrom(fieldType)
|| Character.class.isAssignableFrom(fieldType)
|| Long.class.isAssignableFrom(fieldType)
|| Short.class.isAssignableFrom(fieldType)
|| Double.class.isAssignableFrom(fieldType)
|| Float.class.isAssignableFrom(fieldType)
|| Byte.class.isAssignableFrom(fieldType);
}
Thanks, and if there a easier way to populate everything please let me know.