### Question:
UniqueGenerator implements Generator<T> { @Override public T next() { int retryCount = 0; do { T next = delegate.next(); if (!alreadyGenerated.contains(next)) { alreadyGenerated.add(next); return next; } retryCount++; } while (retryCount <= numberOfRetries); throw new IllegalStateException(on(" ").join("Exhausted", numberOfRetries, "retries trying to generate unique value")); } UniqueGenerator(@Nonnull Generator<T> delegate);  UniqueGenerator(@Nonnull Generator<T> delegate, int numberOfRetries); @Override T next();  }### Answer:
@Test public void shouldGenerateOnlyUniqueValues() { Generator<Integer> uniqueGenerator = new UniqueGenerator<>(new RandomPositiveIntegerGenerator(1, 6), 100); List<Integer> generatedIntegers = newArrayList(); for (int i = 1; i <= 5; i++) { generatedIntegers.add(uniqueGenerator.next()); } assertThat(generatedIntegers, hasSize(5)); assertThat(newHashSet(generatedIntegers), hasSize(5)); }
@Test public void shouldFailAfter10UnsuccessfulAttemptsToGenerateUniqueValue() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Exhausted 10 retries trying to generate unique value"); Generator<String> uniqueGenerator = new UniqueGenerator<>(Generators.ofInstance("One")); try { uniqueGenerator.next(); } catch (IllegalStateException e) { fail("Exception thrown earlier than expected"); } uniqueGenerator.next(); verify(stringGenerator, times(12)).next(); }
@Test public void shouldFailAfterNCustomRetries() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Exhausted 2 retries trying to generate unique value"); Generator<String> uniqueGenerator = new UniqueGenerator<>(Generators.ofInstance("One"), 2); try { uniqueGenerator.next(); } catch (IllegalStateException e) { fail("Exception thrown earlier than expected"); } uniqueGenerator.next(); verify(stringGenerator, times(4)).next(); }