method2testcases
stringlengths
118
6.63k
### Question: CharacterUtils { public static List<Character> filterLetters(List<Character> characters) { return characters.stream().filter(Character::isLetter).collect(toList()); } private CharacterUtils(); static List<Character> collectPrintableCharactersOf(Charset charset); static List<Character> filterLetters(List<Character> characters); }### Answer: @Test void testFilterLetters() { List<Character> characters = filterLetters(asList('a', 'b', '1')); assertThat(characters).containsExactly('a', 'b'); }
### Question: BigDecimalRangeRandomizer implements Randomizer<BigDecimal> { @Override public BigDecimal getRandomValue() { Double delegateRandomValue = delegate.getRandomValue(); BigDecimal randomValue = new BigDecimal(delegateRandomValue); if (scale != null) { randomValue = randomValue.setScale(this.scale, this.roundingMode); } return randomValue; } BigDecimalRangeRandomizer(final Double min, final Double max); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed); BigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale); BigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale, final RoundingMode roundingMode); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale, final RoundingMode roundingMode); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale, final RoundingMode roundingMode); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale, final RoundingMode roundingMode); @Override BigDecimal getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { BigDecimal randomValue = randomizer.getRandomValue(); assertThat(randomValue.doubleValue()).isBetween(min, max); }
### Question: BigDecimalRangeRandomizer implements Randomizer<BigDecimal> { public static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max) { return new BigDecimalRangeRandomizer(min, max); } BigDecimalRangeRandomizer(final Double min, final Double max); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed); BigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale); BigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale, final RoundingMode roundingMode); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale); BigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale, final RoundingMode roundingMode); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final Integer scale, final RoundingMode roundingMode); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale); static BigDecimalRangeRandomizer aNewBigDecimalRangeRandomizer(final Double min, final Double max, final long seed, final Integer scale, final RoundingMode roundingMode); @Override BigDecimal getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewBigDecimalRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: FloatRangeRandomizer extends AbstractRangeRandomizer<Float> { @Override public Float getRandomValue() { return (float) nextDouble(min, max); } FloatRangeRandomizer(final Float min, final Float max); FloatRangeRandomizer(final Float min, final Float max, final long seed); static FloatRangeRandomizer aNewFloatRangeRandomizer(final Float min, final Float max); static FloatRangeRandomizer aNewFloatRangeRandomizer(final Float min, final Float max, final long seed); @Override Float getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Float randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: FloatRangeRandomizer extends AbstractRangeRandomizer<Float> { public static FloatRangeRandomizer aNewFloatRangeRandomizer(final Float min, final Float max) { return new FloatRangeRandomizer(min, max); } FloatRangeRandomizer(final Float min, final Float max); FloatRangeRandomizer(final Float min, final Float max, final long seed); static FloatRangeRandomizer aNewFloatRangeRandomizer(final Float min, final Float max); static FloatRangeRandomizer aNewFloatRangeRandomizer(final Float min, final Float max, final long seed); @Override Float getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewFloatRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: ZonedDateTimeRangeRandomizer extends AbstractRangeRandomizer<ZonedDateTime> { @Override public ZonedDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), min.getZone()); } ZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max); ZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max, final long seed); static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max); static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max, final long seed); @Override ZonedDateTime getRandomValue(); }### Answer: @Test void generatedZonedDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedZonedDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minZonedDateTime, maxZonedDateTime); }
### Question: ZonedDateTimeRangeRandomizer extends AbstractRangeRandomizer<ZonedDateTime> { public static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max) { return new ZonedDateTimeRangeRandomizer(min, max); } ZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max); ZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max, final long seed); static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max); static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max, final long seed); @Override ZonedDateTime getRandomValue(); }### Answer: @Test void whenSpecifiedMinZonedDateTimeIsAfterMaxZonedDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewZonedDateTimeRangeRandomizer(maxZonedDateTime, minZonedDateTime)).isInstanceOf(IllegalArgumentException.class); }
### Question: ShortRangeRandomizer extends AbstractRangeRandomizer<Short> { @Override public Short getRandomValue() { return (short) nextDouble(min, max); } ShortRangeRandomizer(final Short min, final Short max); ShortRangeRandomizer(final Short min, final Short max, final long seed); static ShortRangeRandomizer aNewShortRangeRandomizer(final Short min, final Short max); static ShortRangeRandomizer aNewShortRangeRandomizer(final Short min, final Short max, final long seed); @Override Short getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Short randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: ShortRangeRandomizer extends AbstractRangeRandomizer<Short> { public static ShortRangeRandomizer aNewShortRangeRandomizer(final Short min, final Short max) { return new ShortRangeRandomizer(min, max); } ShortRangeRandomizer(final Short min, final Short max); ShortRangeRandomizer(final Short min, final Short max, final long seed); static ShortRangeRandomizer aNewShortRangeRandomizer(final Short min, final Short max); static ShortRangeRandomizer aNewShortRangeRandomizer(final Short min, final Short max, final long seed); @Override Short getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewShortRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: StringRandomizer extends AbstractRandomizer<String> { @Override public String getRandomValue() { int length = (int) nextDouble(minLength, maxLength); char[] chars = new char[length]; for (int i = 0; i < length; i++) { chars[i] = characterRandomizer.getRandomValue(); } return new String(chars); } StringRandomizer(); StringRandomizer(final Charset charset); StringRandomizer(int maxLength); StringRandomizer(long seed); StringRandomizer(final Charset charset, final long seed); StringRandomizer(final int maxLength, final long seed); StringRandomizer(final int minLength, final int maxLength, final long seed); StringRandomizer(final Charset charset, final int maxLength, final long seed); StringRandomizer(final Charset charset, final int minLength, final int maxLength, final long seed); static StringRandomizer aNewStringRandomizer(); static StringRandomizer aNewStringRandomizer(final Charset charset); static StringRandomizer aNewStringRandomizer(final int maxLength); static StringRandomizer aNewStringRandomizer(final long seed); static StringRandomizer aNewStringRandomizer(final Charset charset, final long seed); static StringRandomizer aNewStringRandomizer(final int maxLength, final long seed); static StringRandomizer aNewStringRandomizer(final int minLength, final int maxLength, final long seed); static StringRandomizer aNewStringRandomizer(final Charset charset, final int maxLength, final long seed); static StringRandomizer aNewStringRandomizer(final Charset charset, final int minLength, final int maxLength, final long seed); @Override String getRandomValue(); }### Answer: @Test void generatedValueMustNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
### Question: ReflectionUtils { public static boolean isMapType(final Class<?> type) { return Map.class.isAssignableFrom(type); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsMapType() { assertThat(ReflectionUtils.isMapType(CustomMap.class)).isTrue(); assertThat(ReflectionUtils.isMapType(Foo.class)).isFalse(); }
### Question: StringDelegatingRandomizer implements Randomizer<String> { @Override public String getRandomValue() { return valueOf(delegate.getRandomValue()); } StringDelegatingRandomizer(final Randomizer<?> delegate); static StringDelegatingRandomizer aNewStringDelegatingRandomizer(final Randomizer<?> delegate); @Override String getRandomValue(); }### Answer: @Test void generatedValueShouldTheSameAs() { String actual = stringDelegatingRandomizer.getRandomValue(); assertThat(actual).isEqualTo(valueOf(object)); }
### Question: CharacterRandomizer extends AbstractRandomizer<Character> { @Override public Character getRandomValue() { return characters.get(random.nextInt(characters.size())); } CharacterRandomizer(); CharacterRandomizer(final Charset charset); CharacterRandomizer(final long seed); CharacterRandomizer(final Charset charset, final long seed); static CharacterRandomizer aNewCharacterRandomizer(); static CharacterRandomizer aNewCharacterRandomizer(final Charset charset); static CharacterRandomizer aNewCharacterRandomizer(final long seed); static CharacterRandomizer aNewCharacterRandomizer(final Charset charset, final long seed); @Override Character getRandomValue(); }### Answer: @Test void generatedValueMustNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void shouldGenerateOnlyAlphabeticLetters() { assertThat(randomizer.getRandomValue()).isBetween('A', 'z'); }
### Question: MapRandomizer implements Randomizer<Map<K, V>> { public static <K, V> MapRandomizer<K, V> aNewMapRandomizer(final Randomizer<K> keyRandomizer, final Randomizer<V> valueRandomizer) { return new MapRandomizer<>(keyRandomizer, valueRandomizer, getRandomSize()); } MapRandomizer(final Randomizer<K> keyRandomizer, final Randomizer<V> valueRandomizer); MapRandomizer(final Randomizer<K> keyRandomizer, final Randomizer<V> valueRandomizer, final int nbEntries); static MapRandomizer<K, V> aNewMapRandomizer(final Randomizer<K> keyRandomizer, final Randomizer<V> valueRandomizer); static MapRandomizer<K, V> aNewMapRandomizer(final Randomizer<K> keyRandomizer, final Randomizer<V> valueRandomizer, final int nbEntries); @Override Map<K, V> getRandomValue(); }### Answer: @Test void specifiedSizeShouldBePositive() { assertThatThrownBy(() -> aNewMapRandomizer(keyRandomizer, valueRandomizer, -3)).isInstanceOf(IllegalArgumentException.class); } @Test void nullKeyRandomizer() { assertThatThrownBy(() -> aNewMapRandomizer(null, valueRandomizer, 3)).isInstanceOf(IllegalArgumentException.class); } @Test void nullValueRandomizer() { assertThatThrownBy(() -> aNewMapRandomizer(keyRandomizer, null, 3)).isInstanceOf(IllegalArgumentException.class); }
### Question: ZoneIdRandomizer extends AbstractRandomizer<ZoneId> { @Override public ZoneId getRandomValue() { List<Map.Entry<String, String>> zoneIds = new ArrayList<>(ZoneId.SHORT_IDS.entrySet()); Map.Entry<String, String> randomZoneId = zoneIds.get(random.nextInt(zoneIds.size())); return ZoneId.of(randomZoneId.getValue()); } ZoneIdRandomizer(); ZoneIdRandomizer(long seed); static ZoneIdRandomizer aNewZoneIdRandomizer(); static ZoneIdRandomizer aNewZoneIdRandomizer(final long seed); @Override ZoneId getRandomValue(); }### Answer: @Test void generatedValueShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
### Question: TimeZoneRandomizer extends AbstractRandomizer<TimeZone> { @Override public TimeZone getRandomValue() { String[] timeZoneIds = TimeZone.getAvailableIDs(); return TimeZone.getTimeZone(timeZoneIds[random.nextInt(timeZoneIds.length)]); } TimeZoneRandomizer(); TimeZoneRandomizer(final long seed); static TimeZoneRandomizer aNewTimeZoneRandomizer(); static TimeZoneRandomizer aNewTimeZoneRandomizer(final long seed); @Override TimeZone getRandomValue(); }### Answer: @Test void generatedValueShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
### Question: ArrayPopulator { Object getRandomArray(final Class<?> fieldType, final RandomizationContext context) { Class<?> componentType = fieldType.getComponentType(); int randomSize = getRandomArraySize(context.getParameters()); Object result = Array.newInstance(componentType, randomSize); for (int i = 0; i < randomSize; i++) { Object randomElement = easyRandom.doPopulateBean(componentType, context); Array.set(result, i, randomElement); } return result; } ArrayPopulator(final EasyRandom easyRandom); }### Answer: @Test void getRandomArray() { when(context.getParameters()).thenReturn(new EasyRandomParameters().collectionSizeRange(INT, INT)); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(STRING); String[] strings = (String[]) arrayPopulator.getRandomArray(String[].class, context); assertThat(strings).containsOnly(STRING); }
### Question: RegularExpressionRandomizer extends FakerBasedRandomizer<String> { @Override public String getRandomValue() { return faker.regexify(removeLeadingAndTailingBoundaryMatchers(regularExpression)); } RegularExpressionRandomizer(final String regularExpression); RegularExpressionRandomizer(final String regularExpression, final long seed); static RegularExpressionRandomizer aNewRegularExpressionRandomizer(final String regularExpression); static RegularExpressionRandomizer aNewRegularExpressionRandomizer(final String regularExpression, final long seed); @Override String getRandomValue(); }### Answer: @Test void leadingBoundaryMatcherIsRemoved() { RegularExpressionRandomizer randomizer = new RegularExpressionRandomizer("^A"); String actual = randomizer.getRandomValue(); then(actual).isEqualTo("A"); } @Test void tailingBoundaryMatcherIsRemoved() { RegularExpressionRandomizer randomizer = new RegularExpressionRandomizer("A$"); String actual = randomizer.getRandomValue(); then(actual).isEqualTo("A"); } @Test void leadingAndTailingBoundaryMatcherIsRemoved() { RegularExpressionRandomizer randomizer = new RegularExpressionRandomizer("^A$"); String actual = randomizer.getRandomValue(); then(actual).isEqualTo("A"); }
### Question: ReflectionUtils { public static boolean isJdkBuiltIn(final Class<?> type) { return type.getName().startsWith("java.util"); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsJdkBuiltIn() { assertThat(ReflectionUtils.isJdkBuiltIn(ArrayList.class)).isTrue(); assertThat(ReflectionUtils.isJdkBuiltIn(CustomList.class)).isFalse(); }
### Question: ReflectionUtils { public static Class<?> getWrapperType(Class<?> primitiveType) { for(PrimitiveEnum p : PrimitiveEnum.values()) { if(p.getType().equals(primitiveType)) { return p.getClazz(); } } return primitiveType; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void getWrapperTypeTest() { assertThat(ReflectionUtils.getWrapperType(Byte.TYPE)).isEqualTo(Byte.class); assertThat(ReflectionUtils.getWrapperType(Short.TYPE)).isEqualTo(Short.class); assertThat(ReflectionUtils.getWrapperType(Integer.TYPE)).isEqualTo(Integer.class); assertThat(ReflectionUtils.getWrapperType(Long.TYPE)).isEqualTo(Long.class); assertThat(ReflectionUtils.getWrapperType(Double.TYPE)).isEqualTo(Double.class); assertThat(ReflectionUtils.getWrapperType(Float.TYPE)).isEqualTo(Float.class); assertThat(ReflectionUtils.getWrapperType(Boolean.TYPE)).isEqualTo(Boolean.class); assertThat(ReflectionUtils.getWrapperType(Character.TYPE)).isEqualTo(Character.class); assertThat(ReflectionUtils.getWrapperType(String.class)).isEqualTo(String.class); }
### Question: ReflectionUtils { public static Optional<Method> getReadMethod(Field field) { String fieldName = field.getName(); Class<?> fieldClass = field.getDeclaringClass(); String capitalizedFieldName = fieldName.substring(0, 1).toUpperCase(ENGLISH) + fieldName.substring(1); Optional<Method> getter = getPublicMethod("get" + capitalizedFieldName, fieldClass); if (getter.isPresent()) { return getter; } return getPublicMethod("is" + capitalizedFieldName, fieldClass); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testGetReadMethod() throws NoSuchFieldException { assertThat(ReflectionUtils.getReadMethod(PrimitiveFieldsWithDefaultValuesBean.class.getDeclaredField("b"))).isEmpty(); final Optional<Method> readMethod = ReflectionUtils.getReadMethod(Foo.class.getDeclaredField("bar")); assertThat(readMethod).isNotNull(); assertThat(readMethod.get().getName()).isEqualTo("getBar"); }
### Question: ReflectionUtils { public static <T extends Annotation> T getAnnotation(Field field, Class<T> annotationType) { return field.getAnnotation(annotationType) == null ? getAnnotationFromReadMethod(getReadMethod(field).orElse(null), annotationType) : field.getAnnotation(annotationType); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testGetAnnotation() throws NoSuchFieldException { Field field = AnnotatedBean.class.getDeclaredField("fieldAnnotation"); assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isInstanceOf(NotNull.class); field = AnnotatedBean.class.getDeclaredField("methodAnnotation"); assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isInstanceOf(NotNull.class); field = AnnotatedBean.class.getDeclaredField("noAnnotation"); assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isNull(); }
### Question: ReflectionUtils { public static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType) { final Optional<Method> readMethod = getReadMethod(field); return field.isAnnotationPresent(annotationType) || readMethod.isPresent() && readMethod.get().isAnnotationPresent(annotationType); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsAnnotationPresent() throws NoSuchFieldException { Field field = AnnotatedBean.class.getDeclaredField("fieldAnnotation"); assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isTrue(); field = AnnotatedBean.class.getDeclaredField("methodAnnotation"); assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isTrue(); field = AnnotatedBean.class.getDeclaredField("noAnnotation"); assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isFalse(); }
### Question: ReflectionUtils { public static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface) { Collection<?> collection = new ArrayList<>(); if (List.class.isAssignableFrom(collectionInterface)) { collection = new ArrayList<>(); } else if (NavigableSet.class.isAssignableFrom(collectionInterface)) { collection = new TreeSet<>(); } else if (SortedSet.class.isAssignableFrom(collectionInterface)) { collection = new TreeSet<>(); } else if (Set.class.isAssignableFrom(collectionInterface)) { collection = new HashSet<>(); } else if (BlockingDeque.class.isAssignableFrom(collectionInterface)) { collection = new LinkedBlockingDeque<>(); } else if (Deque.class.isAssignableFrom(collectionInterface)) { collection = new ArrayDeque<>(); } else if (TransferQueue.class.isAssignableFrom(collectionInterface)) { collection = new LinkedTransferQueue<>(); } else if (BlockingQueue.class.isAssignableFrom(collectionInterface)) { collection = new LinkedBlockingQueue<>(); } else if (Queue.class.isAssignableFrom(collectionInterface)) { collection = new LinkedList<>(); } return collection; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testGetEmptyImplementationForCollectionInterface() { Collection<?> collection = ReflectionUtils.getEmptyImplementationForCollectionInterface(List.class); assertThat(collection).isInstanceOf(ArrayList.class).isEmpty(); }
### Question: ReflectionUtils { public static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize) { rejectUnsupportedTypes(fieldType); Collection<?> collection; try { collection = (Collection<?>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.equals(ArrayBlockingQueue.class)) { collection = new ArrayBlockingQueue<>(initialSize); } else { collection = (Collection<?>) new ObjenesisStd().newInstance(fieldType); } } return collection; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void createEmptyCollectionForArrayBlockingQueue() { Collection<?> collection = ReflectionUtils.createEmptyCollectionForType(ArrayBlockingQueue.class, INITIAL_CAPACITY); assertThat(collection).isInstanceOf(ArrayBlockingQueue.class).isEmpty(); assertThat(((ArrayBlockingQueue<?>) collection).remainingCapacity()).isEqualTo(INITIAL_CAPACITY); } @Test void synchronousQueueShouldBeRejected() { assertThatThrownBy(() -> ReflectionUtils.createEmptyCollectionForType(SynchronousQueue.class, INITIAL_CAPACITY)).isInstanceOf(UnsupportedOperationException.class); } @Test void delayQueueShouldBeRejected() { assertThatThrownBy(() -> ReflectionUtils.createEmptyCollectionForType(DelayQueue.class, INITIAL_CAPACITY)).isInstanceOf(UnsupportedOperationException.class); }
### Question: ReflectionUtils { public static <T> List<Field> getDeclaredFields(T type) { return new ArrayList<>(asList(type.getClass().getDeclaredFields())); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testGetDeclaredFields() { BigDecimal javaVersion = new BigDecimal(System.getProperty("java.specification.version")); if (javaVersion.compareTo(new BigDecimal("12")) >= 0) { assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(21); } else if (javaVersion.compareTo(new BigDecimal("9")) >= 0) { assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22); } else { assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20); } }
### Question: ReflectionUtils { public static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface) { Map<?, ?> map = new HashMap<>(); if (ConcurrentNavigableMap.class.isAssignableFrom(mapInterface)) { map = new ConcurrentSkipListMap<>(); } else if (ConcurrentMap.class.isAssignableFrom(mapInterface)) { map = new ConcurrentHashMap<>(); } else if (NavigableMap.class.isAssignableFrom(mapInterface)) { map = new TreeMap<>(); } else if (SortedMap.class.isAssignableFrom(mapInterface)) { map = new TreeMap<>(); } return map; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void getEmptyImplementationForMapInterface() { Map<?, ?> map = ReflectionUtils.getEmptyImplementationForMapInterface(SortedMap.class); assertThat(map).isInstanceOf(TreeMap.class).isEmpty(); }
### Question: CollectionUtils { public static <T> T randomElementOf(final List<T> list) { if (list.isEmpty()) { return null; } return list.get(nextInt(0, list.size())); } private CollectionUtils(); static T randomElementOf(final List<T> list); }### Answer: @Test void testRandomElementOf() { String[] elements = {"foo", "bar"}; String element = CollectionUtils.randomElementOf(asList(elements)); assertThat(element).isIn(elements); }
### Question: EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }### Answer: @Test void generatedBeansNumberShouldBeEqualToSpecifiedNumber() { Stream<Person> persons = easyRandom.objects(Person.class, 2); assertThat(persons).hasSize(2).hasOnlyElementsOfType(Person.class); } @Test void whenSpecifiedNumberOfBeansToGenerateIsNegative_thenShouldThrowAnIllegalArgumentException() { assertThatThrownBy(() -> easyRandom.objects(Person.class, -2)).isInstanceOf(IllegalArgumentException.class); }
### Question: ReflectionUtils { public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testGetInheritedFields() { assertThat(ReflectionUtils.getInheritedFields(SocialPerson.class)).hasSize(11); }
### Question: ReflectionUtils { public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsStatic() throws Exception { assertThat(ReflectionUtils.isStatic(Human.class.getField("SERIAL_VERSION_UID"))).isTrue(); }
### Question: PriorityComparator implements Comparator<Object> { @Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; } @Override int compare(final Object o1, final Object o2); }### Answer: @Test void testCompare() { assertThat(priorityComparator.compare(foo, bar)).isGreaterThan(0); List<Object> objects = Arrays.asList(foo,bar); objects.sort(priorityComparator); assertThat(objects).containsExactly(bar, foo); }
### Question: CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }### Answer: @Test void rawInterfaceCollectionTypesMustBeReturnedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawInterfaceList"); Collection<?> collection = collectionPopulator.getRandomCollection(field, context); assertThat(collection).isEmpty(); } @Test void rawConcreteCollectionTypesMustBeReturnedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawConcreteList"); Collection<?> collection = collectionPopulator.getRandomCollection(field, context); assertThat(collection).isEmpty(); } @Test void typedInterfaceCollectionTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(STRING); Field field = Foo.class.getDeclaredField("typedInterfaceList"); @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>) collectionPopulator.getRandomCollection(field, context); assertThat(collection).containsExactly(STRING, STRING); } @Test void typedConcreteCollectionTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(STRING); Field field = Foo.class.getDeclaredField("typedConcreteList"); @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>) collectionPopulator.getRandomCollection(field, context); assertThat(collection).containsExactly(STRING, STRING); }
### Question: ReflectionUtils { public static boolean isInterface(final Class<?> type) { return type.isInterface(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsInterface() { assertThat(ReflectionUtils.isInterface(List.class)).isTrue(); assertThat(ReflectionUtils.isInterface(Mammal.class)).isTrue(); assertThat(ReflectionUtils.isInterface(MammalImpl.class)).isFalse(); assertThat(ReflectionUtils.isInterface(ArrayList.class)).isFalse(); }
### Question: DefaultExclusionPolicy implements ExclusionPolicy { public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; } boolean shouldBeExcluded(final Field field, final RandomizerContext context); boolean shouldBeExcluded(final Class<?> type, final RandomizerContext context); }### Answer: @Test void staticFieldsShouldBeExcluded() throws NoSuchFieldException { Field field = Human.class.getDeclaredField("SERIAL_VERSION_UID"); boolean actual = exclusionPolicy.shouldBeExcluded(field, randomizerContext); assertThat(actual).isTrue(); }
### Question: MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }### Answer: @Test void rawInterfaceMapTypesMustBeGeneratedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawMap"); Map<?, ?> randomMap = mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); } @Test void rawConcreteMapTypesMustBeGeneratedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("concreteMap"); Map<?, ?> randomMap = mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); } @Test void typedInterfaceMapTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(FOO, BAR); Field field = Foo.class.getDeclaredField("typedMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).containsExactly(entry(FOO, BAR)); } @Test void typedConcreteMapTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(FOO, BAR); Field field = Foo.class.getDeclaredField("typedConcreteMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).containsExactly(entry(FOO, BAR)); } @Test void notAddNullKeysToMap() throws NoSuchFieldException { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(null); Field field = Foo.class.getDeclaredField("typedConcreteMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); }
### Question: ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } @Override T createInstance(Class<T> type, RandomizerContext context); }### Answer: @Test void concreteClassesShouldBeCreatedAsExpected() { String string = objenesisObjectFactory.createInstance(String.class, context); assertThat(string).isNotNull(); } @Test void whenNoConcreteTypeIsFound_thenShouldThrowAnInstantiationError() { Mockito.when(context.getParameters().isScanClasspathForConcreteTypes()).thenReturn(true); assertThatThrownBy(() -> objenesisObjectFactory.createInstance(AbstractFoo.class, context)).isInstanceOf(InstantiationError.class); }
### Question: EnumRandomizer extends AbstractRandomizer<E> { public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); } EnumRandomizer(final Class<E> enumeration); EnumRandomizer(final Class<E> enumeration, final long seed); EnumRandomizer(final Class<E> enumeration, final E... excludedValues); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final long seed); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final E... excludedValues); @Override E getRandomValue(); }### Answer: @Test void should_throw_an_exception_when_all_values_are_excluded() { assertThatThrownBy(() -> aNewEnumRandomizer(Gender.class, Gender.values())).isInstanceOf(IllegalArgumentException.class); }
### Question: ReflectionUtils { public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsAbstract() { assertThat(ReflectionUtils.isAbstract(Foo.class)).isFalse(); assertThat(ReflectionUtils.isAbstract(Bar.class)).isTrue(); }
### Question: OptionalRandomizer extends AbstractRandomizer<T> { @Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; } OptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); static Randomizer<T> aNewOptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); @Override T getRandomValue(); }### Answer: @Test void whenOptionalPercentIsOneHundredThenShouldGenerateValue() { assertThat(optionalRandomizer.getRandomValue()) .isEqualTo(NAME); }
### Question: DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { @Override public Double getRandomValue() { return nextDouble(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Double randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDoubleRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }### Answer: @Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
### Question: ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { @Override public Byte getRandomValue() { return (byte) nextDouble(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Byte randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewByteRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }### Answer: @Test void generatedOffsetDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedOffsetDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minOffsetDateTime, maxOffsetDateTime); }
### Question: OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }### Answer: @Test void whenSpecifiedMinOffsetDateTimeIsAfterMaxOffsetDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetDateTimeRangeRandomizer(maxOffsetDateTime, minOffsetDateTime)).isInstanceOf(IllegalArgumentException.class); }
### Question: ReflectionUtils { public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsPublic() { assertThat(ReflectionUtils.isPublic(Foo.class)).isTrue(); assertThat(ReflectionUtils.isPublic(Dummy.class)).isFalse(); }
### Question: LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }### Answer: @Test void generatedLocalDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
### Question: LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }### Answer: @Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
### Question: InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }### Answer: @Test void generatedInstantShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedInstantShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minInstant, maxInstant); }
### Question: InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }### Answer: @Test void whenSpecifiedMinInstantIsAfterMaxInstant_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewInstantRangeRandomizer(maxInstant, minInstant)).isInstanceOf(IllegalArgumentException.class); }
### Question: BigIntegerRangeRandomizer implements Randomizer<BigInteger> { @Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { BigInteger randomValue = randomizer.getRandomValue(); assertThat(randomValue.intValue()).isBetween(min, max); }
### Question: BigIntegerRangeRandomizer implements Randomizer<BigInteger> { public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewBigIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }### Answer: @Test void generatedOffsetTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedOffsetTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
### Question: ReflectionUtils { public static boolean isArrayType(final Class<?> type) { return type.isArray(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsArrayType() { assertThat(ReflectionUtils.isArrayType(int[].class)).isTrue(); assertThat(ReflectionUtils.isArrayType(Foo.class)).isFalse(); }
### Question: OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }### Answer: @Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
### Question: LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }### Answer: @Test void generatedLocalTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
### Question: LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }### Answer: @Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
### Question: DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }### Answer: @Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
### Question: DateRangeRandomizer extends AbstractRangeRandomizer<Date> { public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }### Answer: @Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
### Question: YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }### Answer: @Test void generatedYearMonthShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedYearMonthShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYearMonth, maxYearMonth); }
### Question: YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }### Answer: @Test void whenSpecifiedMinYearMonthIsAfterMaxYearMonth_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearMonthRangeRandomizer(maxYearMonth, minYearMonth)).isInstanceOf(IllegalArgumentException.class); }
### Question: ReflectionUtils { public static boolean isEnumType(final Class<?> type) { return type.isEnum(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsEnumType() { assertThat(ReflectionUtils.isEnumType(Gender.class)).isTrue(); assertThat(ReflectionUtils.isEnumType(Foo.class)).isFalse(); }
### Question: YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }### Answer: @Test void generatedYearShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedYearShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYear, maxYear); }
### Question: YearRangeRandomizer extends AbstractRangeRandomizer<Year> { public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }### Answer: @Test void whenSpecifiedMinYearIsAfterMaxYear_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearRangeRandomizer(maxYear, minYear)).isInstanceOf(IllegalArgumentException.class); }
### Question: LongRangeRandomizer extends AbstractRangeRandomizer<Long> { @Override public Long getRandomValue() { return (long) nextDouble(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Long randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: LongRangeRandomizer extends AbstractRangeRandomizer<Long> { public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLongRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }### Answer: @Test void generatedLocalDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDateTime, maxDateTime); }
### Question: LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }### Answer: @Test void whenSpecifiedMinDateTimeIsAfterMaxDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateTimeRangeRandomizer(maxDateTime, minDateTime)).isInstanceOf(IllegalArgumentException.class); }
### Question: IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { @Override public Integer getRandomValue() { return (int) nextDouble(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }### Answer: @Test void generatedValueShouldBeWithinSpecifiedRange() { Integer randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
### Question: IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }### Answer: @Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
### Question: ReflectionUtils { public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }### Answer: @Test void testIsCollectionType() { assertThat(ReflectionUtils.isCollectionType(CustomList.class)).isTrue(); assertThat(ReflectionUtils.isCollectionType(Foo.class)).isFalse(); }
### Question: SpanishWordParser implements WordParser { @Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); } @Inject SpanishWordParser(final @Named(FALLBACK_RHYMES) List<String> defaultRhymes); @Override StressType stressType(final String word); @Override boolean rhyme(final String word1, final String word2); @Override String phoneticRhymePart(final String word); @Override boolean isLetter(final char letter); @Override boolean isWord(final String text); @Override String getDefaultRhyme(); }### Answer: @Test public void testGetNumberPhoneticRhymePart() { assertEquals(wordParser.phoneticRhymePart("-1"), "uno"); assertEquals(wordParser.phoneticRhymePart("0"), "ero"); assertEquals(wordParser.phoneticRhymePart("dos"), "os"); assertEquals(wordParser.phoneticRhymePart("3521637"), "ete"); assertEquals(wordParser.phoneticRhymePart("350000"), "il"); assertEquals(wordParser.phoneticRhymePart("5000000"), "ones"); }
### Question: RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }### Answer: @Test(expectedExceptions = IOException.class) public void testDeleteUnexistingRhyme() throws IOException { store.delete("Unexisting"); } @Test public void testDeleteWithoutText() throws IOException { store.delete(null); store.delete(""); }
### Question: RedisStore { @VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }### Answer: @Test public void testSum() { assertEquals(store.sum("foo"), "acbd18db4cc2f85cedef654fccc4a4d8"); assertEquals(store.sum("bar"), "37b51d194a7513e45b56f6524f2d51f2"); }
### Question: Keymaker { public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); } Keymaker(final String namespace); Keymaker build(final String... namespaces); @Override String toString(); }### Answer: @Test public void testKeymaker() { checkKeymaker(""); checkKeymaker(":"); checkKeymaker("test"); checkKeymaker(":test:"); checkKeymaker("test::"); checkKeymaker("::test"); checkKeymaker("test:test2"); }
### Question: ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); @Override void execute(); }### Answer: @Test public void testExecuteWithExistingRhyme() throws TwitterException { ReplyCommand replyCommand = createReplyCommand("Este test es casi perfecto"); replyCommand.execute(); assertTrue(twitter.getLastUpdatedStatus().contains("Rima por defecto")); } @Test public void testExecuteWithScreenNameRhyme() throws TwitterException { ReplyCommand replyCommand = createReplyCommand("Rima esto con el usuario"); replyCommand.execute(); assertTrue(twitter.getLastUpdatedStatus().contains("Esta rima es infame")); }
### Question: WordUtils { public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }### Answer: @Test public void testCapitalize() { assertEquals(capitalize(null), null); assertEquals(capitalize(""), ""); assertEquals(capitalize("hola"), "Hola"); assertEquals(capitalize("hOLA"), "HOLA"); }
### Question: WordUtils { public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }### Answer: @Test public void testGetLastWord() { assertEquals(getLastWord(null), ""); assertEquals(getLastWord(""), ""); assertEquals(getLastWord("hola"), "hola"); assertEquals(getLastWord("hola adios"), "adios"); assertEquals(getLastWord("hola ."), "."); }
### Question: WordUtils { public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }### Answer: @Test public void testIsNumber() { assertFalse(isNumber(null)); assertFalse(isNumber("")); assertFalse(isNumber("a")); assertFalse(isNumber("-a")); assertFalse(isNumber("23a")); assertTrue(isNumber("-1")); assertTrue(isNumber("0")); assertTrue(isNumber("12345")); }
### Question: Configuration { static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); } private Configuration(); static final String CONFIG_FILE; static final String REDIS_HOST; static final String REDIS_PORT; static final String REDIS_PASSWORD; static final String FALLBACK_RHYMES; static final String DEFAULT_RHYMES; }### Answer: @Test public void testGetConfigValue() { assertNull(getConfigValue("unexisting")); assertEquals(getConfigValue(REDIS_HOST), "localhost"); }
### Question: Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); static final String CONFIG_FILE; static final String REDIS_HOST; static final String REDIS_PORT; static final String REDIS_PASSWORD; static final String FALLBACK_RHYMES; static final String DEFAULT_RHYMES; }### Answer: @Test public void testGetRequiredConfigValue() { assertEquals(getRequiredConfigValue(REDIS_HOST), "localhost"); } @Test(expectedExceptions = ConfigurationException.class) public void testGetUnexistingRequiredConfigValue() { getRequiredConfigValue("unexisting"); }
### Question: RedisStore { public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }### Answer: @Test public void testFindAll() throws IOException { assertEquals(store.findAll().size(), 2); }
### Question: RedisStore { public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }### Answer: @Test public void testGetRhyme() throws IOException { assertNull(store.getRhyme("no hay rima")); assertEquals(store.getRhyme("¿Hay algo que rime con tres?"), "Me escondo y no me ves"); assertEquals(store.getRhyme("Nada rima con dos"), "Ya son veintidós!!"); }
### Question: DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }### Answer: @Test public void validateIndexes( ) { boolean punched[] = new boolean[index.getXYZ()]; for (int x = 0; x < mX; x++) for (int y = 0; y < mY; y++) for (int z = 0; z < mZ; z++) { final int idx = index.rollup(x,y,z); assertFalse(punched[idx]); punched[idx] = true; } for (int p = 0; p < punched.length; ++p) { assertTrue(punched[p]); } } @Test(expected = RuntimeException.class) public void badX( ) { index.rollup(mX, 0,0); } @Test(expected = RuntimeException.class) public void badY( ) { index.rollup(0, mY,0); } @Test(expected = RuntimeException.class) public void badZ( ) { index.rollup(0,0,mZ); } @Test public void badZmsg( ) { try { index.rollup(0,0,mZ); Assert.fail("should have thrown an exception"); } catch (RuntimeException re) { } }
### Question: EventRateLimiter { public boolean isOkayToFireEventNow(){ long totalElapsedTimeNow = timeRightNow()-startTime; int currentTimeRegimeIndex = 0; for (int i=0; i<intervals.length; i++) { currentTimeRegimeIndex = i; if (totalElapsedTimeNow < intervals[i][TIME_INTERVAL_REGIME]){ break; } } if (timeSinceLastApprovedEvent() < intervals[currentTimeRegimeIndex][TIME_INTERVAL_PER_REGIME]){ return false; } else { timeOfLastEvent = timeRightNow(); return true; } } EventRateLimiter(long[][] specifiedIntervals); EventRateLimiter(); boolean isOkayToFireEventNow(); static void main(String[] args); }### Answer: @Test public void test() { try { EventRateLimiter eventRateLimiter = new EventRateLimiter(); long testStartTime = System.currentTimeMillis(); System.out.println("Starting at " + testStartTime); int approvedEventCount = 0; while (System.currentTimeMillis() < testStartTime + 60000) { if (eventRateLimiter.isOkayToFireEventNow()) { approvedEventCount++; System.out.println("Now it is "+ System.currentTimeMillis()); } } if ((approvedEventCount > 67) && (approvedEventCount < 73)) { System.out.println(String.valueOf(approvedEventCount)+ " events approved in one minute"); } else { System.out.println(String.valueOf(approvedEventCount)+" events approved in one minute is out of expected bounds"); fail(String.valueOf(approvedEventCount)+" events approved in one minute is out of expected bounds"); } } catch (Exception e) { fail("Exception occured: "+e.getMessage()); } }
### Question: User implements java.io.Serializable, Matchable, Immutable { public boolean isPublisher() { return Arrays.asList(publishers).contains(userName); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); static final String[] publishers; static final User tempUser; static final String VCELL_GUEST; }### Answer: @Test public void publisherTest( ) { User u = new User("schaff", testKey( )); Assert.assertTrue(u.isPublisher()); u = new User("fido", testKey( )); Assert.assertFalse(u.isPublisher()); }
### Question: User implements java.io.Serializable, Matchable, Immutable { public boolean isTestAccount() { return isTestAccount(getName( )); } User(String userid, KeyValue key); static String createGuestErrorMessage(String theOffendingOp); static boolean isGuest(String checkThisName); boolean compareEqual(Matchable obj); boolean equals(Object obj); KeyValue getID(); String getName(); int hashCode(); boolean isPublisher(); boolean isTestAccount(); static boolean isTestAccount(String accountName); String toString(); static final String[] publishers; static final User tempUser; static final String VCELL_GUEST; }### Answer: @Test public void testAcctTest( ) { User u = new User("vcelltestaccount", testKey( )); Assert.assertTrue(u.isTestAccount()); u = new User("fido", testKey( )); Assert.assertFalse(u.isTestAccount()); }
### Question: VCCollections { public static <T> boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp) { return equal(a,b,cmp,null); } static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp); static boolean equal(Collection<T> a, Collection<T> b, Comparator<T> cmp , Collection<Delta<T> > diffs); }### Answer: @Test public <T> void ctest( ) { ArrayList<Delta<Integer>> dt = new ArrayList<VCCollections.Delta<Integer>>( ); b.addAll(a); assertTrue(VCCollections.equal(a, b, cmp, null)); assertTrue(VCCollections.equal(a, b, cmp, dt)); for (int i = 0; i < 10 ;i++) { Collections.shuffle(b); assertTrue(VCCollections.equal(a, b, cmp, null)); assertTrue(VCCollections.equal(a, b, cmp, dt)); } b.add(7); assertFalse(VCCollections.equal(a, b, cmp, null)); assertFalse(VCCollections.equal(a, b, cmp, dt)); a.add(8); assertFalse(VCCollections.equal(a, b, cmp, null)); assertFalse(VCCollections.equal(a, b, cmp, dt)); }
### Question: CircularList extends AbstractCollection<E> { @Override public boolean add(E e) { storage.add(e); while (storage.size() > capacity()) { storage.pop(); } return true; } CircularList(int capacity); int capacity(); @Override boolean add(E e); @Override Iterator<E> iterator(); @Override int size(); }### Answer: @Test public void tryIt( ) { insert(7,10); validate(7,8,9,10); list.clear(); insert(1,23); validate(19,20,21,22,23); list.add(7); validate(20,21,22,23,7); }
### Question: CachedDataBaseReferenceReader { public static CachedDataBaseReferenceReader getCachedReader( ) { CachedDataBaseReferenceReader r = dbReader.get(); if (r != null) { return r; } synchronized(dbReader) { r = dbReader.get(); if (r != null) { return r; } r = new CachedDataBaseReferenceReader(); dbReader = new SoftReference<CachedDataBaseReferenceReader>(r); } return r; } private CachedDataBaseReferenceReader( ); static CachedDataBaseReferenceReader getCachedReader( ); String getMoleculeDataBaseReference(String molId); String getChEBIName(String chebiId); String getGOTerm(String goId); String getMoleculeDataBaseReference(String db, String id); }### Answer: @Ignore @Test public void fetchAndConsume( ) { ReferenceQueue<CachedDataBaseReferenceReader> rq = new ReferenceQueue<CachedDataBaseReferenceReader>(); WeakReference<CachedDataBaseReferenceReader> weakR = new WeakReference<CachedDataBaseReferenceReader>( CachedDataBaseReferenceReader.getCachedReader(),rq); boolean outOfMem = false; ArrayList<int[]> pig = new ArrayList<int[]>( ); for (int size = 10;!outOfMem;size*=10) { try { assertFalse(weakR.isEnqueued()); pig.add(new int[size]); CachedDataBaseReferenceReader w = weakR.get( ); assertTrue(w == CachedDataBaseReferenceReader.getCachedReader()); } catch(OutOfMemoryError error) { assertTrue(weakR.isEnqueued()); assertTrue(weakR.get( ) == null); outOfMem = true; } } pig.clear(); CachedDataBaseReferenceReader dbReader = CachedDataBaseReferenceReader.getCachedReader(); assertTrue(dbReader != null); }
### Question: HtcProxy { public static boolean isMyJob(HtcJobInfo htcJobInfo){ return htcJobInfo.getJobName().startsWith(jobNamePrefix()); } HtcProxy(CommandService commandService, String htcUser); static boolean isMyJob(HtcJobInfo htcJobInfo); abstract void killJobSafe(HtcJobInfo htcJobInfo); abstract void killJobUnsafe(HtcJobID htcJobId); abstract void killJobs(String htcJobSubstring); abstract Map<HtcJobInfo,HtcJobStatus> getJobStatus(List<HtcJobInfo> requestedHtcJobInfos); abstract HtcJobID submitJob(String jobName, File sub_file_internal, File sub_file_external, ExecutableCommand.Container commandSet, int ncpus, double memSize, Collection<PortableCommand> postProcessingCommands, SimulationTask simTask,File primaryUserDirExternal); abstract HtcJobID submitOptimizationJob(String jobName, File sub_file_internal, File sub_file_external,File optProblemInput,File optProblemOutput); abstract HtcProxy cloneThreadsafe(); abstract Map<HtcJobInfo,HtcJobStatus> getRunningJobs(); abstract PartitionStatistics getPartitionStatistics(); final CommandService getCommandService(); final String getHtcUser(); static SimTaskInfo getSimTaskInfoFromSimJobName(String simJobName); static String createHtcSimJobName(SimTaskInfo simTaskInfo); static void writeUnixStyleTextFile(File file, String javaString); abstract String getSubmissionFileExtension(); static MemLimitResults getMemoryLimit(String vcellUserid,KeyValue simID,SolverDescription solverDescription,double estimatedMemSizeMB); static boolean isStochMultiTrial(SimulationTask simTask); static final Logger LG; final static String HTC_SIMULATION_JOB_NAME_PREFIX; static final boolean bDebugMemLimit; }### Answer: @Test public void test_isMyJob(){ System.setProperty(PropertyLoader.vcellServerIDProperty,"ALPHA"); Assert.assertTrue(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_ALPHA_115785823_0_0"))); Assert.assertFalse(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_BETA_115785823_0_0"))); System.setProperty(PropertyLoader.vcellServerIDProperty,"BETA"); Assert.assertTrue(HtcProxy.isMyJob(new HtcJobInfo(new HtcJobID("1200725", BatchSystemType.SLURM),"V_BETA_115785823_0_0"))); }
### Question: UnitSymbol implements Serializable { public String getUnitSymbolAsInfix() { return rootNode.toInfix(); } UnitSymbol(String unitStr); String getUnitSymbolAsInfix(); String getUnitSymbolAsInfixWithoutFloatScale(); double getNumericScale(); String getUnitSymbol(); String getUnitSymbolUnicode(); String getUnitSymbolHtml(); }### Answer: @Test public void example( ) { Assert.assertEquals("uM*s^-1", new UnitSymbol("uM.s-1").getUnitSymbolAsInfix()); }
### Question: VCellThreadChecker { public static void checkCpuIntensiveInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (guiThreadChecker.isEventDispatchThread() && cpuSuppressed.get() == 0) { System.out.println("!!!!!!!!!!!!!! --calling cpu intensive method from swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); }### Answer: @Test public void notSwingCheck( ) { VCellThreadChecker.checkCpuIntensiveInvocation(); checkQuiet( ); } @Test public void swingCheckSupp( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) { subCall( ); VCellThreadChecker.checkCpuIntensiveInvocation(); } } }); checkQuiet( ); } @Test(expected=IllegalStateException.class) public void swingCheckNotSupp( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) { } VCellThreadChecker.checkCpuIntensiveInvocation(); } }); checkQuiet( ); }
### Question: VCellThreadChecker { public static void checkSwingInvocation() { if (guiThreadChecker == null){ System.out.println("!!!!!!!!!!!!!! --VCellThreadChecker.setGUIThreadChecker() not set"); Thread.dumpStack(); }else if (!guiThreadChecker.isEventDispatchThread()) { System.out.println("!!!!!!!!!!!!!! --calling swing from non-swing thread-----"); Thread.dumpStack(); } } static void setGUIThreadChecker(GUIThreadChecker argGuiThreadChecker); static void checkRemoteInvocation(); static void checkSwingInvocation(); static void checkCpuIntensiveInvocation(); }### Answer: @Test public void swingCheck( ) throws InvocationTargetException, InterruptedException { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { VCellThreadChecker.checkSwingInvocation(); } }); checkQuiet( ); }
### Question: GenericUtils { @SuppressWarnings("unchecked") public static <T> java.util.List<T> convert(java.util.List<?> list, Class<T> clzz) { for (Object o : list) { if (!clzz.isAssignableFrom(o.getClass()) ) { throw new RuntimeException("invalid list conversion, " + clzz.getName() + " list contains " + o.getClass()); } } return (List<T>) list; } @SuppressWarnings("unchecked") static java.util.List<T> convert(java.util.List<?> list, Class<T> clzz); }### Answer: @Test public void goodConvert( ) { ArrayList<Object> al = new ArrayList<Object>( ); for (int i = 0; i < 5; i++) { al.add(Integer.valueOf(i)); } List<Integer> asIntArray = GenericUtils.convert(al, Integer.class); for (int i = 0; i < 5; i++) { assertTrue(asIntArray.get(i) == i); } } @Test(expected = RuntimeException.class) public void badConvert( ) { ArrayList<Object> al = new ArrayList<Object>( ); for (int i = 0; i < 5; i++) { al.add(Integer.valueOf(i)); } List<String> asIntArray = GenericUtils.convert(al, String.class); System.out.println(asIntArray); }
### Question: StreamingResultSet implements Iterator<Map<String, Node>>, Closeable { public StreamingResultSet(BufferedReader in) throws IOException { this.in = in; tsvParser = new TsvParser(in); if ((currentTuple = tsvParser.getTuple()) == null) { hasNext = false; } } StreamingResultSet(BufferedReader in); StreamingResultSet(HttpURLConnection conn); @Override Map<String, Node> next(); String[] getResultVars(); @Override void close(); @Override boolean hasNext(); }### Answer: @Test public void testStreamingResultSet() throws IOException { BufferedReader bufferedReader = new BufferedReader(new StringReader("?s\t?p\t?o\n" + "<http: + "<http: + "<http: List<Map<String, Node>> result = new ArrayList<>(); try (StreamingResultSet resultSet = new StreamingResultSet(bufferedReader)) { assertArrayEquals(new String[] {"s", "p", "o"}, resultSet.getResultVars()); int rowsRead = 0; assertEquals(rowsRead, resultSet.getRowNumber()); while (resultSet.hasNext()) { Map<String, Node> rs = resultSet.next(); System.out.println(rs); result.add(rs); rowsRead++; assertEquals(rowsRead, resultSet.getRowNumber()); } } assertEquals(3, result.size()); }
### Question: TsvParser { private static Optional<Node> parseNode(String nodeString) { try { return Optional.of(NodeFactoryExtra.parseNode(nodeString)); } catch (RiotException e) { log.error("Parsing of value '{}' failed: {}", nodeString, e.getMessage()); return Optional.empty(); } } TsvParser(BufferedReader in); Map<String, Node> getTuple(); }### Answer: @Test public void testResourceEnding() throws IOException { Map<String, Node> result = parseSingleTuple("?s\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: } @Test public void testEmptyVariablesInResult() throws IOException { Map<String, Node> result = parseSingleTuple("?s\t?p\t?o\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: assertFalse(result.containsKey("p")); assertEquals(NodeFactoryExtra.parseNode("\"o2\""), result.get("o")); } @Test public void testMultipleEmptyVariablesInResult() throws IOException { Map<String, Node> result; result = parseSingleTuple("?s\t?p\t?o\n" + "\t\t\"o2\"\n"); assertFalse(result.containsKey("s")); assertFalse(result.containsKey("p")); assertEquals(NodeFactoryExtra.parseNode("\"o2\""), result.get("o")); result = parseSingleTuple("?s\t?p\t?o\n" + "<http: assertEquals(NodeFactoryExtra.parseNode("<http: assertFalse(result.containsKey("p")); assertFalse(result.containsKey("o")); result = parseSingleTuple("?s\t?p\t?o\n" + "\t\t\t\n"); assertEquals(0, result.size()); } @Test public void testNodeParser() { Node parseNode = NodeFactoryExtra.parseNode("\"Hallo \\\"Echo\\\"!\"@de"); assertEquals("de", parseNode.getLiteralLanguage()); assertEquals("Hallo \"Echo\"!", parseNode.getLiteralValue()); }
### Question: FeaturePluginToMavenDependencyConverter { static Set<Dependency> convert(Set<IFeaturePlugin> featurePlugins) { return featurePlugins.stream().map(FeaturePluginToMavenDependencyConverter::convert).collect(Collectors.toSet()); } }### Answer: @Test public void testConversionForFXDependency() { IFeaturePlugin featurePlugin = Mockito.mock(IFeaturePlugin.class); Mockito.when(featurePlugin.getId()).thenReturn(FEATURE_PLUGIN_ID_FX); Mockito.when(featurePlugin.getVersion()).thenReturn(FEATURE_PLUGIN_VERSION_FX); Set<Dependency> dependencies = FeaturePluginToMavenDependencyConverter.convert(new HashSet<>(Arrays.asList(featurePlugin))); assertThat(dependencies.size(), equalTo(1)); if (dependencies.size() == 1) { Dependency dependency = dependencies.iterator().next(); assertThat(dependency.getGroupId(), equalTo("at.bestsolution.efxclipse.rt")); assertThat(dependency.getArtifactId(), equalTo(FEATURE_PLUGIN_ID_FX)); assertThat(dependency.getVersion(), equalTo("3.0.0")); } } @Test public void testConversionForNonFXDependency() { IFeaturePlugin featurePlugin = Mockito.mock(IFeaturePlugin.class); Mockito.when(featurePlugin.getId()).thenReturn(FEATURE_PLUGIN_ID_NON_FX); Mockito.when(featurePlugin.getVersion()).thenReturn(FEATURE_PLUGIN_VERSION_NON_FX); Set<Dependency> dependencies = FeaturePluginToMavenDependencyConverter.convert(new HashSet<>(Arrays.asList(featurePlugin))); assertThat(dependencies.size(), equalTo(1)); if (dependencies.size() == 1) { Dependency dependency = dependencies.iterator().next(); assertThat(dependency.getGroupId(), equalTo("at.bestsolution.efxclipse.eclipse")); assertThat(dependency.getArtifactId(), equalTo(FEATURE_PLUGIN_ID_NON_FX)); assertThat(dependency.getVersion(), equalTo("0.10.0")); } }