UniqueValueGenerator { public static <S> S generateUniqueValue(Supplier<S> uniqueValueSupplier, Predicate<S> valueTest, short limit) { S uniqueValue = null; short iterationCounter = 0; do { final S tempValue = uniqueValueSupplier.get(); uniqueValue = valueTest.test(tempValue) ? tempValue : null; iterationCounter++; } while (uniqueValue == null && iterationCounter < limit); if (uniqueValue == null || (uniqueValue instanceof String && !StringUtils .hasText((String) uniqueValue))) { StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Unique value cannot be generated in "); errorBuilder.append(iterationCounter); errorBuilder.append(" trials."); throw new UniqueValueGeneratorException(errorBuilder.toString()); } return uniqueValue; }  static S generateUniqueValue(Supplier<S> uniqueValueSupplier,
			Predicate<S> valueTest, short limit);  }
@Test public void testGenerateUniqueValue_Success_First_Trial() { AtomicInteger counter = new AtomicInteger(0); String value = UniqueValueGenerator.generateUniqueValue( () -> TEST_VALUE, v -> { counter.incrementAndGet(); return true; }, LIMIT); assertEquals(TEST_VALUE, value); assertEquals(1, counter.get()); }
@Test public void testGenerateUniqueValue_Success_Last_Trial() { AtomicInteger counter = new AtomicInteger(0); String value = UniqueValueGenerator.generateUniqueValue( () -> TEST_VALUE, v -> counter.incrementAndGet() >= LIMIT, LIMIT); assertEquals(TEST_VALUE, value); assertEquals(LIMIT, counter.get()); }
@Test public void testGenerateUniqueValue_Throws_UniqueValueGeneratorException_Last_Trial1() { AtomicInteger counter = new AtomicInteger(0); thrown.expect(UniqueValueGeneratorException.class); String value = null; try { value = UniqueValueGenerator.generateUniqueValue(() -> TEST_VALUE, v -> { counter.incrementAndGet(); return false; }, LIMIT); } catch (Exception e) { assertEquals(null, value); assertEquals(LIMIT, counter.get()); throw e; } }
@Test public void testGenerateUniqueValue_Throws_UniqueValueGeneratorException_Last_Trial2() { AtomicInteger counter = new AtomicInteger(0); thrown.expect(UniqueValueGeneratorException.class); String value = null; try { value = UniqueValueGenerator.generateUniqueValue(() -> TEST_VALUE, v -> counter.incrementAndGet() > LIMIT, LIMIT); } catch (Exception e) { assertEquals(null, value); assertEquals(LIMIT, counter.get()); throw e; } }