### Question:
RandomFromCollectionGenerator implements Generator<T> { @Override public T next() { return exclusiveIndex > 0 ? items.get(random.nextInt(exclusiveIndex)) : null; } RandomFromCollectionGenerator(@Nonnull Collection<T> items); @SafeVarargs  RandomFromCollectionGenerator(T... items); @Override T next();  }### Answer:
@Test public void shouldPickRandomItemFromCollection() { Set<String> countries = newHashSet(getISOCountries()); Generator<String> countriesGenerator = new RandomFromCollectionGenerator<>(countries); for (int i = 0; i < 1000; i++) { countries.remove(countriesGenerator.next()); } assertThat(countries, hasSize(lessThan(30))); }
@Test public void shouldPickRandomItemFromArray() { String[] countries = getISOCountries(); Set<String> countriesSet = newHashSet(getISOCountries()); Generator<String> countriesGenerator = new RandomFromCollectionGenerator<>(countries); for (int i = 0; i < 1000; i++) { countriesSet.remove(countriesGenerator.next()); } assertThat(countriesSet, hasSize(lessThan(30))); }
@Test public void shouldNotFailGenerationIfCollectionIsEmpty() { Generator<String> someGenerator = new RandomFromCollectionGenerator<>(Collections.<String>emptyList()); for (int i = 0; i < 3; i++) { String nullValue = someGenerator.next(); assertThat(nullValue, nullValue()); } }
@Test public void shouldSometimesReturnLastItemInCollection() { Generator<Integer> someGenerator = new RandomFromCollectionGenerator<>(1,2); for (int i = 0; i < 100; i++) { Integer generated = someGenerator.next(); if (generated % 2 == 0) return; } fail("Number 2 was not generated"); }
@Test public void shouldAlwaysReturnSameElementForSingletonCollection() { String someString = "Hi"; Generator<String> someGenerator = new RandomFromCollectionGenerator<>(singleton(someString)); for (int i = 0; i < 3; i++) { String generatedString = someGenerator.next(); assertThat(generatedString, is(someString)); } }