src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
MockableClient extends OkHttpClient { @Override public Call newCall(Request request) { if (shouldMockRequest(request)) { return mockedClient.newCall(request); } else { return realClient.newCall(request); } } MockableClient(Registry registry, OkHttpClient realClient, ReplaceEndpoint...
@Test public void notInRegistry_CallRealEndpoint() { givenWhenFunctionReturns(true); givenEndpointInRegistry(false); testee.newCall(REQUEST); verify(realClient).newCall(REQUEST); verify(mockClient, never()).newCall(any(Request.class)); } @Test public void inRegistryAndShouldMock_CallMockedEndpoint() { givenWhenFunction...
ReplaceEndpointClient extends OkHttpClient { @Override public Call newCall(Request request) { return realClient.newCall( withReplacedEndpoint(request) ); } ReplaceEndpointClient(String newEndpoint, OkHttpClient realClient); @Override Call newCall(Request request); }
@Test public void replaceUrl() { Request realRequest = new Request.Builder() .url(REAL_BASE_URL + PATH) .build(); testee.newCall(realRequest); ArgumentCaptor<Request> requestCaptor = ArgumentCaptor.forClass(Request.class); Mockito.verify(realClient).newCall(requestCaptor.capture()); Request sentRequest = requestCaptor....
Registry { public boolean isInRegistry(String url) { if (getMockedEndpointsMethod == null) { return false; } Set<String> mockedEndpoints = getMockedEndpoints(); for (String endpoint : mockedEndpoints) { if (endpointMatches(endpoint, url)) { return true; } } return false; } Registry(); boolean isInRegistry(String url); ...
@Test public void inRegistry_Yes_PartialMatch() throws Exception { FakeRegistry.setRegistry(new HashSet<>(asList( "/path3/path4", "/path1/path2" ))); boolean result = testee.isInRegistry("http: assertTrue(result); } @Test public void inRegistry_Yes_PathParameters() throws Exception { FakeRegistry.setRegistry(new HashSe...
IEXOrderBook implements OrderBook { public void priceLevelUpdate(final IEXPriceLevelUpdateMessage iexPriceLevelUpdateMessage) { switch (iexPriceLevelUpdateMessage.getIexMessageType()) { case PRICE_LEVEL_UPDATE_SELL: askSide.priceLevelUpdate(iexPriceLevelUpdateMessage); break; case PRICE_LEVEL_UPDATE_BUY: bidSide.priceL...
@Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForUnknownMessageType() { final IEXPriceLevelUpdateMessage iexPriceLevelUpdateMessage = anIEXPriceLevelUpdateMessage() .withIEXMessageType(IEXMessageType.OPERATIONAL_HALT_STATUS) .build(); final IEXOrderBook orderBook = new IEXOrderBook(TE...
PriceLevel { @Override public int hashCode() { return Objects.hash(symbol, timestamp, price, size); } PriceLevel( final String symbol, final long timestamp, final IEXPrice price, final int size); String getSymbol(); long getTimestamp(); IEXPrice getPrice(); int getSize();...
@Test public void shouldTwoInstancesWithSameValuesBeEqual() { PriceLevel priceLevel_1 = defaultPriceLevel(); PriceLevel priceLevel_2 = defaultPriceLevel(); assertThat(priceLevel_1).isEqualTo(priceLevel_2); assertThat(priceLevel_1.hashCode()).isEqualTo(priceLevel_2.hashCode()); }
AbstractMemory extends SearchableMemory implements IMemory { public void addMemorySource(IMemorySource source) { logger.logp(FINEST,"AbstractMemory","addMemorySource","Added memory range {0}-{1}",new Object[]{Long.toHexString(source.getBaseAddress()), Long.toHexString(source.getTopAddress()) }); if (GLOBAL_CACHE_ENABLE...
@Test public void testFindPattern() { AbstractMemory sut = new MockMemory(ByteOrder.BIG_ENDIAN); sut.addMemorySource(new MockMemorySource(new byte[] { 0x0 }, 0, 0, 100)); sut .addMemorySource(new MockMemorySource(new byte[] { 0xA }, 0, 100, 100)); sut .addMemorySource(new MockMemorySource(new byte[] { 0xB }, 0, 200, 10...
IMemoryImageInputStream extends ImageInputStreamImpl { @Override public long getStreamPosition() throws IOException { return address; } IMemoryImageInputStream(IMemory memory, long startingAddress); @Override int read(byte[] buffer, int offset, int length); @Override int read(); @Override long getStreamPosition(); @Ove...
@Test public void testGetStreamPosition() throws Exception { AbstractMemory memory = new MockMemory(ByteOrder.BIG_ENDIAN); memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xA0}, 0, 0x10000, 0x10000)); memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xB0}, 0, 0x20000, 0x10000)); IMemoryImag...
IMemoryImageInputStream extends ImageInputStreamImpl { @Override public void seek(long pos) throws IOException { address = pos; } IMemoryImageInputStream(IMemory memory, long startingAddress); @Override int read(byte[] buffer, int offset, int length); @Override int read(); @Override long getStreamPosition(); @Override ...
@Test public void testSeek() throws Exception { AbstractMemory memory = new MockMemory(ByteOrder.BIG_ENDIAN); memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xA0}, 0, 0x10000, 0x10000)); memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xB0}, 0, 0x20000, 0x10000)); IMemoryImageInputStream ...
IMemoryImageInputStream extends ImageInputStreamImpl { @Override public int read(byte[] buffer, int offset, int length) throws IOException { int read = 0; try { read = memory.getBytesAt(address, buffer,offset,length); } catch (MemoryFault f) { if (f.getAddress() == address) { return -1; } else { read = (int)(f.getAddre...
@Test public void testEOFBlocks() throws Exception { AbstractMemory memory = new MockMemory(ByteOrder.BIG_ENDIAN); memory.addMemorySource(new MockMemorySource(new byte[] { (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF}, 0, 0x10000, 0x10000)); memory.addMemorySource(new UnbackedMemorySource(0x20000, 0x10000, "Deliberat...
Addresses { public static boolean greaterThan(long a, long b) { if (signBitsSame(a, b)) { return a > b; } else { return a < b; } } static boolean greaterThan(long a, long b); static boolean greaterThanOrEqual(long a, long b); static boolean lessThan(long a, long b); static boolean lessThanOrEqual(long a, long b); }
@Test public void testGreaterThan() { assertTrue(Addresses.greaterThan(1, 0)); assertTrue(Addresses.greaterThan(Long.MAX_VALUE, Long.MAX_VALUE - 1)); assertFalse(Addresses.greaterThan(7, 8)); assertTrue(Addresses.greaterThan(0xFFFFFFFFFFFFFFFFL, 0)); assertTrue(Addresses.greaterThan(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFF...
Addresses { public static boolean lessThan(long a, long b) { if (signBitsSame(a, b)) { return a < b; } else { return a > b; } } static boolean greaterThan(long a, long b); static boolean greaterThanOrEqual(long a, long b); static boolean lessThan(long a, long b); static boolean lessThanOrEqual(long a, long b); }
@Test public void testLessThan() { assertFalse(Addresses.lessThan(1, 0)); assertFalse(Addresses.lessThan(Long.MAX_VALUE, Long.MAX_VALUE - 1)); assertTrue(Addresses.lessThan(7, 8)); assertFalse(Addresses.lessThan(0xFFFFFFFFFFFFFFFFL, 0)); assertFalse(Addresses .lessThan(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFEL)); assert...
SqlBuilder { public String build() { addCopyTable(); addColumnNames(); addFileConfig(); return getSql(); } SqlBuilder(EntityInfo entityInfo); String build(); void addCopyTable(); void addColumnNames(); void addFileConfig(); String getSql(); }
@Test public void testCompleteQuery() { SqlBuilder sqlBuilder = new SqlBuilder(buildEntity()); String sql = sqlBuilder.build(); String expectedSql = "COPY simple_table (column1, column2) " + "FROM STDIN WITH (ENCODING 'UTF-8', DELIMITER '\t', HEADER false)"; assertEquals(expectedSql, sql); }
LoadDataEscaper { public String escapeForLoadFile(String text) { if (text == null) { return null; } int firstEscapableChar = findFirstEscapableChar(text); if (firstEscapableChar == -1) { return text; } StringBuilder sb = new StringBuilder(text.substring(0, firstEscapableChar)); int textLength = text.length(); for (int ...
@Test public void testEscapeFieldTermination() { String text = "1234\tvalue\t5678\t"; String escaped = escaper.escapeForLoadFile(text); assertEquals("1234" + ESCAPED_BY_CHAR + FIELD_TERMINATED_CHAR + "value" + ESCAPED_BY_CHAR + FIELD_TERMINATED_CHAR + "5678" + ESCAPED_BY_CHAR + FIELD_TERMINATED_CHAR, escaped); logger.i...
FieldTypeInspector { public Optional<EntityFieldType> getFieldType(Class<?> javaType) { FieldTypeEnum value = null; if (Long.class.equals(javaType) || long.class.equals(javaType)) { value = FieldTypeEnum.LONG; } else if (Boolean.class.equals(javaType) || boolean.class.equals(javaType)) { value = FieldTypeEnum.BOOLEAN; ...
@Test public void booleanPrimitiveTest() { EntityFieldType type = getField("booleanPrimitive"); assertTrue(type.isPrimitive()); assertEquals(FieldTypeEnum.BOOLEAN, type.getFieldType()); } @Test public void booleanObjectTest() { EntityFieldType type = getField("booleanObject"); assertFalse(type.isPrimitive()); assertEqu...
PgCopyEscaper { public String escapeForStdIn(String text) { if (text == null) { return null; } int firstEscapableChar = findFirstEscapableChar(text); if (firstEscapableChar == -1) { return text; } StringBuilder sb = new StringBuilder(text.substring(0, firstEscapableChar)); int textLength = text.length(); for (int i = f...
@Test public void testNoEscapeNeeded() { String text = "Some text with no escape neeed"; String escaped = escaper.escapeForStdIn(text); assertEquals(text, escaped); } @Test public void testEscapeEscapedByChar() { String text = "Some text with some \\ escape char \\\\ to change"; String escaped = escaper.escapeForStdIn(...
SqlBuilder { public String build() { addLoadDataIntoTable(); addFileConfig(); addColumnNames(); return getSql(); } SqlBuilder(EntityInfo entityInfo); String build(); void addLoadDataIntoTable(); void addFileConfig(); void addColumnNames(); String getSql(); }
@Test public void testCompleteQuery() { SqlBuilder sqlBuilder = new SqlBuilder(buildEntity()); String sql = sqlBuilder.build(); String expectedSql = "LOAD DATA LOCAL INFILE '' INTO TABLE simple_table " + "CHARACTER SET UTF8 FIELDS TERMINATED BY '\t' ENCLOSED BY '' " + "ESCAPED BY '\\\\' LINES TERMINATED BY '\n' STARTIN...
UriUtils { public static URI getParent(final URI uri) { if (isRoot(uri)) { return null; } else { final URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve("."); final String parentStr = parent.toString(); return isRoot(parent) ? parent : URI.create(parentStr.substring(0, parentStr.length() - 1));...
@Test public void test() { final URI root1 = URI.create(INTERNAL_URI_PREFIX + "/"); assertNull("parent should be null", UriUtils.getParent(root1)); } @Test public void testChildOfRoot() { final URI uri = URI.create(INTERNAL_URI_PREFIX + "/test"); assertEquals("incorrect parent", URI.create(INTERNAL_URI_PREFIX + "/"), U...
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> cha...
@Test void testFilterLetters() { List<Character> characters = filterLetters(asList('a', 'b', '1')); assertThat(characters).containsExactly('a', 'b'); }
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); } ret...
@Test void generatedValueShouldBeWithinSpecifiedRange() { BigDecimal randomValue = randomizer.getRandomValue(); assertThat(randomValue.doubleValue()).isBetween(min, max); }
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 Doub...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewBigDecimalRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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 aNewFloatRangeRando...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Float randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewFloatRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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 =...
@Test void generatedZonedDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedZonedDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minZonedDateTime, maxZonedDateTime); }
ZonedDateTimeRangeRandomizer extends AbstractRangeRandomizer<ZonedDateTime> { public static ZonedDateTimeRangeRandomizer aNewZonedDateTimeRangeRandomizer(final ZonedDateTime min, final ZonedDateTime max) { return new ZonedDateTimeRangeRandomizer(min, max); } ZonedDateTimeRangeRandomizer(final ZonedDateTime min, final Z...
@Test void whenSpecifiedMinZonedDateTimeIsAfterMaxZonedDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewZonedDateTimeRangeRandomizer(maxZonedDateTime, minZonedDateTime)).isInstanceOf(IllegalArgumentException.class); }
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 aNewShortRangeRando...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Short randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewShortRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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(); St...
@Test void generatedValueMustNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
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> getInheritedField...
@Test void testIsMapType() { assertThat(ReflectionUtils.isMapType(CustomMap.class)).isTrue(); assertThat(ReflectionUtils.isMapType(Foo.class)).isFalse(); }
StringDelegatingRandomizer implements Randomizer<String> { @Override public String getRandomValue() { return valueOf(delegate.getRandomValue()); } StringDelegatingRandomizer(final Randomizer<?> delegate); static StringDelegatingRandomizer aNewStringDelegatingRandomizer(final Randomizer<?> delegate); @Override String ge...
@Test void generatedValueShouldTheSameAs() { String actual = stringDelegatingRandomizer.getRandomValue(); assertThat(actual).isEqualTo(valueOf(object)); }
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, fin...
@Test void generatedValueMustNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void shouldGenerateOnlyAlphabeticLetters() { assertThat(randomizer.getRandomValue()).isBetween('A', 'z'); }
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 Rand...
@Test void specifiedSizeShouldBePositive() { assertThatThrownBy(() -> aNewMapRandomizer(keyRandomizer, valueRandomizer, -3)).isInstanceOf(IllegalArgumentException.class); } @Test void nullKeyRandomizer() { assertThatThrownBy(() -> aNewMapRandomizer(null, valueRandomizer, 3)).isInstanceOf(IllegalArgumentException.class)...
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()); } Zone...
@Test void generatedValueShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
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 ...
@Test void generatedValueShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
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++) {...
@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).containsO...
RegularExpressionRandomizer extends FakerBasedRandomizer<String> { @Override public String getRandomValue() { return faker.regexify(removeLeadingAndTailingBoundaryMatchers(regularExpression)); } RegularExpressionRandomizer(final String regularExpression); RegularExpressionRandomizer(final String regularExpression, fin...
@Test void leadingBoundaryMatcherIsRemoved() { RegularExpressionRandomizer randomizer = new RegularExpressionRandomizer("^A"); String actual = randomizer.getRandomValue(); then(actual).isEqualTo("A"); } @Test void tailingBoundaryMatcherIsRemoved() { RegularExpressionRandomizer randomizer = new RegularExpressionRandomiz...
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> getInher...
@Test void testIsJdkBuiltIn() { assertThat(ReflectionUtils.isJdkBuiltIn(ArrayList.class)).isTrue(); assertThat(ReflectionUtils.isJdkBuiltIn(CustomList.class)).isFalse(); }
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 Su...
@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....
ReflectionUtils { public static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (!fieldType.isPrimitive()) { return false; } Object fieldValue = getFieldValue(object, field); if (fieldValue == null) { return false;...
@Test void testIsPrimitiveFieldWithDefaultValue() throws Exception { Class<PrimitiveFieldsWithDefaultValuesBean> defaultValueClass = PrimitiveFieldsWithDefaultValuesBean.class; PrimitiveFieldsWithDefaultValuesBean defaultValueBean = new PrimitiveFieldsWithDefaultValuesBean(); assertThat(ReflectionUtils.isPrimitiveField...
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" + capi...
@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(); as...
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(); @Suppres...
@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.ge...
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 ...
@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.isAnnotat...
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(collection...
@Test void testGetEmptyImplementationForCollectionInterface() { Collection<?> collection = ReflectionUtils.getEmptyImplementationForCollectionInterface(List.class); assertThat(collection).isInstanceOf(ArrayList.class).isEmpty(); }
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(Ar...
@Test void createEmptyCollectionForArrayBlockingQueue() { Collection<?> collection = ReflectionUtils.createEmptyCollectionForType(ArrayBlockingQueue.class, INITIAL_CAPACITY); assertThat(collection).isInstanceOf(ArrayBlockingQueue.class).isEmpty(); assertThat(((ArrayBlockingQueue<?>) collection).remainingCapacity()).isE...
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); stati...
@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) { a...
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 = n...
@Test void getEmptyImplementationForMapInterface() { Map<?, ?> map = ReflectionUtils.getEmptyImplementationForMapInterface(SortedMap.class); assertThat(map).isInstanceOf(TreeMap.class).isEmpty(); }
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); }
@Test void testRandomElementOf() { String[] elements = {"foo", "bar"}; String element = CollectionUtils.randomElementOf(asList(elements)); assertThat(element).isIn(elements); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize...
@Test void generatedBeansShouldBeCorrectlyPopulated() { Person person = easyRandom.nextObject(Person.class); validatePerson(person); } @Test void shouldFailIfSetterInvocationFails() { EasyRandom easyRandom = new EasyRandom(); Throwable thrown = catchThrowable(() -> easyRandom.nextObject(Salary.class)); assertThat(throw...
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 e...
@Test void generatedBeansNumberShouldBeEqualToSpecifiedNumber() { Stream<Person> persons = easyRandom.objects(Person.class, 2); assertThat(persons).hasSize(2).hasOnlyElementsOfType(Person.class); } @Test void whenSpecifiedNumberOfBeansToGenerateIsNegative_thenShouldThrowAnIllegalArgumentException() { assertThatThrownBy...
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;...
@Test void testGetInheritedFields() { assertThat(ReflectionUtils.getInheritedFields(SocialPerson.class)).hasSize(11); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwa...
@Test void whenSkipRandomizerIsRegisteredForTheField_thenTheFieldShouldBeSkipped() throws Exception { Field name = Human.class.getDeclaredField("name"); Human human = new Human(); randomizer = new SkipRandomizer(); RandomizationContext context = new RandomizationContext(Human.class, new EasyRandomParameters()); when(ra...
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> getInheritedF...
@Test void testIsStatic() throws Exception { assertThat(ReflectionUtils.isStatic(Human.class.getField("SERIAL_VERSION_UID"))).isTrue(); }
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); }
@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); }
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(); Collectio...
@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...
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<?> t...
@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(); }
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> fieldExclusionPred...
@Test void staticFieldsShouldBeExcluded() throws NoSuchFieldException { Field field = Human.class.getDeclaredField("SERIAL_VERSION_UID"); boolean actual = exclusionPolicy.shouldBeExcluded(field, randomizerContext); assertThat(actual).isTrue(); }
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(fieldTy...
@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 rawConcreteMapTypesMustBeGener...
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 (randomConcre...
@Test void concreteClassesShouldBeCreatedAsExpected() { String string = objenesisObjectFactory.createInstance(String.class, context); assertThat(string).isNotNull(); } @Test void whenNoConcreteTypeIsFound_thenShouldThrowAnInstantiationError() { Mockito.when(context.getParameters().isScanClasspathForConcreteTypes()).the...
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 ...
@Test void should_throw_an_exception_when_all_values_are_excluded() { assertThatThrownBy(() -> aNewEnumRandomizer(Gender.class, Gender.values())).isInstanceOf(IllegalArgumentException.class); }
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> getI...
@Test void testIsAbstract() { assertThat(ReflectionUtils.isAbstract(Foo.class)).isFalse(); assertThat(ReflectionUtils.isAbstract(Bar.class)).isTrue(); }
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 Randomi...
@Test void whenOptionalPercentIsOneHundredThenShouldGenerateValue() { assertThat(optionalRandomizer.getRandomValue()) .isEqualTo(NAME); }
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 aNewDoubleRangeRa...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Double randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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 Doub...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDoubleRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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 D...
@Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
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 ...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Byte randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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); ...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewByteRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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 maxNanoSecond...
@Test void generatedOffsetDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedOffsetDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minOffsetDateTime, maxOffsetDateTime); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min...
@Test void whenSpecifiedMinOffsetDateTimeIsAfterMaxOffsetDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetDateTimeRangeRandomizer(maxOffsetDateTime, minOffsetDateTime)).isInstanceOf(IllegalArgumentException.class); }
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> getInher...
@Test void testIsPublic() { assertThat(ReflectionUtils.isPublic(Foo.class)).isTrue(); assertThat(ReflectionUtils.isPublic(Dummy.class)).isFalse(); }
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...
@Test void generatedLocalDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
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); LocalDateRangeRandom...
@Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
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); } ...
@Test void generatedInstantShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedInstantShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minInstant, maxInstant); }
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...
@Test void whenSpecifiedMinInstantIsAfterMaxInstant_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewInstantRangeRandomizer(maxInstant, minInstant)).isInstanceOf(IllegalArgumentException.class); }
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 se...
@Test void generatedValueShouldBeWithinSpecifiedRange() { BigInteger randomValue = randomizer.getRandomValue(); assertThat(randomValue.intValue()).isBetween(min, max); }
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 ...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewBigIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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); r...
@Test void generatedOffsetTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedOffsetTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
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)...
@Test void testIsArrayType() { assertThat(ReflectionUtils.isArrayType(int[].class)).isTrue(); assertThat(ReflectionUtils.isArrayType(Foo.class)).isFalse(); }
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); OffsetTime...
@Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
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); retu...
@Test void generatedLocalTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
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); LocalTimeRangeRandom...
@Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
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 ...
@Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
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); ...
@Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
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); l...
@Test void generatedYearMonthShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedYearMonthShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYearMonth, maxYearMonth); }
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); YearMonthRangeRandom...
@Test void whenSpecifiedMinYearMonthIsAfterMaxYearMonth_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearMonthRangeRandomizer(maxYearMonth, minYearMonth)).isInstanceOf(IllegalArgumentException.class); }
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); ...
@Test void testIsEnumType() { assertThat(ReflectionUtils.isEnumType(Gender.class)).isTrue(); assertThat(ReflectionUtils.isEnumType(Foo.class)).isFalse(); }
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...
@Test void generatedYearShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedYearShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYear, maxYear); }
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); ...
@Test void whenSpecifiedMinYearIsAfterMaxYear_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearRangeRandomizer(maxYear, minYear)).isInstanceOf(IllegalArgumentException.class); }
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 ...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Long randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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); ...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLongRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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.get...
@Test void generatedLocalDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); } @Test void generatedLocalDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDateTime, maxDateTime); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final L...
@Test void whenSpecifiedMinDateTimeIsAfterMaxDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateTimeRangeRandomizer(maxDateTime, minDateTime)).isInstanceOf(IllegalArgumentException.class); }
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 a...
@Test void generatedValueShouldBeWithinSpecifiedRange() { Integer randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
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...
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
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> get...
@Test void testIsCollectionType() { assertThat(ReflectionUtils.isCollectionType(CustomList.class)).isTrue(); assertThat(ReflectionUtils.isCollectionType(Foo.class)).isFalse(); }
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 ...
@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.phoneticRhy...
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 = getUniqueIdK...
@Test(expectedExceptions = IOException.class) public void testDeleteUnexistingRhyme() throws IOException { store.delete("Unexisting"); } @Test public void testDeleteWithoutText() throws IOException { store.delete(null); store.delete(""); }
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_PAS...
@Test public void testSum() { assertEquals(store.sum("foo"), "acbd18db4cc2f85cedef654fccc4a4d8"); assertEquals(store.sum("bar"), "37b51d194a7513e45b56f6524f2d51f2"); }
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(); }
@Test public void testKeymaker() { checkKeymaker(""); checkKeymaker(":"); checkKeymaker("test"); checkKeymaker(":test:"); checkKeymaker("test::"); checkKeymaker("::test"); checkKeymaker("test:test2"); }
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 wi...
@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 TwitterExc...
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 capit...
@Test public void testCapitalize() { assertEquals(capitalize(null), null); assertEquals(capitalize(""), ""); assertEquals(capitalize("hola"), "Hola"); assertEquals(capitalize("hOLA"), "HOLA"); }
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 capital...
@Test public void testGetLastWord() { assertEquals(getLastWord(null), ""); assertEquals(getLastWord(""), ""); assertEquals(getLastWord("hola"), "hola"); assertEquals(getLastWord("hola adios"), "adios"); assertEquals(getLastWord("hola ."), "."); }