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 getManufacturedPojo(final Class
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 allFields = getAllFields(targetClass, Predicates.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
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.