java-自动使用随机数据填充原始属性?

是否有一个Java库可以帮助创建用于测试的类的实例? 一种检查bean的属性并用随机数据填充它的函数。
我基本上是在寻找Java等效于C#的对象Hydrator。

prasopes asked 2020-08-01T12:21:00Z
7个解决方案
52 votes

您可以使用PoDaM:

PodamFactory factory = new PodamFactoryImpl();
Pojo myPojo = factory.manufacturePojo(Pojo.class);
pk1 answered 2020-08-01T12:21:10Z
21 votes

看一下随机豆:

[HTTPS://GitHub.com/笨啊是/random-beans]

它允许您用随机数据填充Java对象图。

希望能帮助到你问候

Mahmoud Ben Hassine answered 2020-08-01T12:21:43Z
13 votes

我不知道框架,但是自己编写其中一个非常简单。 复杂性来自非简单属性,即对象关联。 这样的东西处理基础知识,然后再处理:

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();
    }
}
Ryan Stewart answered 2020-08-01T12:22:03Z
5 votes

您可以检出randomizer用于生成随机数据。此库可帮助根据给定的Model类创建随机数据。

public class Person {

   @FirstName
   String mFirstName;

   @LastName
   String mLastName;

   @Number(min = 14,max = 25,decimals = 0)
   int age;

   @DateValue( from = "01 Jan 1990",to = "31 Dec 2002" , customFormat = "dd MMM yyyy")
   String dateOfBirth;

   @Email
   String  mEmailId;

   @StreetAddress
   public String streetAddress;

   @State
   public String state;

   //Person can have minimum 1 Phone number and maximum 3 phone number
   @Phone(country = Phone.Country.INDIA)
   @CollectionDescriptor(min = 1,max = 3) 
   List<String> phones;

}

//Generate random 100 Person(Model Class) object 
Generator<Person> generator = new Generator<>(Person.class);  
List<Person> persons = generator.generate(100);                          

由于使用注释可以访问许多内置数据生成器,因此您也可以构建自定义数据生成器。建议您阅读库页面上提供的文档。

Ronak Poriya answered 2020-08-01T12:22:27Z
5 votes

[https://github.com/benas/random-beans]为我完成了工作,而PoDam因“流利的”设置员而失败,并且Ryan Stewart的答案对于复制粘贴不完整,因为对未公开的类的引用 !使用random-beans就像:

Auction auction = EnhancedRandom.random(Auction.class);

摇篮:

testCompile ('io.github.benas:random-beans:3.4.0')
Juri Reinsalu answered 2020-08-01T12:22:52Z
1 votes

在测试方面,我们小组在JUnit和Mockito方面取得了一些成功。 这是Mockito答案的链接。

我不确定用随机数据填充是否将是有意义的测试。 也许更有意义的测试是测试正常,边界和错误条件。

rajah9 answered 2020-08-01T12:23:16Z
0 votes

我在这里使用反射和递归来获取我要测试的坚固对象中的所有字段。 我也正在使用PODAM,我希望有人会发现它有用。

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;
    }

和一些辅助方法。 代码可能并不完美,但是可以工作:)。

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);
}

谢谢,如果有更简单的方法来填充所有内容,请告诉我。

LazerBanana answered 2020-08-01T12:23:45Z
translate from https://stackoverflow.com:/questions/7067734/fill-primitive-properties-with-random-data-automatically