1
\$\begingroup\$

I was running some rightsizing tests and had to blast random objects of my various class types. Here is the code I came up with.

private static <T> T random(Class<?> recordClass) {

    Constructor<?>[] constructors = recordClass.getConstructors();
    Constructor<?> maxParamConstructor = constructors[0];

    for (Constructor<?> check : constructors) {
        if (check.getParameterCount() > maxParamConstructor.getParameterCount())
            maxParamConstructor = check;
    }

    if (maxParamConstructor.getParameterCount() > 0) {

        Type[] types = maxParamConstructor.getGenericParameterTypes();
        Object[] params = new Object[types.length];

        for (int index = 0; index < types.length; index++) {
            params[index] = getRandom(types[index].getTypeName());
        }

        return (T) maxParamConstructor.newInstance(params);
    } else
        return (T) recordClass.newInstance();
}

private static Object getRandom(String type) {

    switch (type) {

        //TODO add others
        case "java.lang.Long":
            return ThreadLocalRandom.current().nextLong();
        case "java.lang.Boolean":
            return ThreadLocalRandom.current().nextBoolean();
        case "java.lang.String":
            return UUID.randomUUID().toString();
        case "java.lang.CharSequence":
            return UUID.randomUUID().toString();
        case "java.lang.Double":
            return ThreadLocalRandom.current().nextDouble();

        default:
            return random(Class.forName(type));
    }
}

Was wondering if it would give me trouble during my tests. Is it any good ? thanks.

\$\endgroup\$
  • 1
    \$\begingroup\$ I try to avoid randomness in tests because you are then testing different conditions every time you run the test. Did the test fail because I changed the code or because it was testing some new combination of random objects? There's no way to know. \$\endgroup\$ – Michael Jan 6 '17 at 15:01
  • \$\begingroup\$ well this does make sense, thanks for your input :) I also noticed my compressions would get screwed this way \$\endgroup\$ – Dexter Jan 8 '17 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.