DescribedCollection implements Iterable<T> { public List<T> itemsList() { if (List.class.isAssignableFrom(items.getClass())) { return Collections.unmodifiableList((List<T>) items); } throw new IllegalStateException("Tried to get a non-list collection as list!"); } DescribedCollection(RepositoryName source, Collection<T> items);  DescribedCollection(RepositoryName source, T... items); RepositoryName source(); Collection<T> items(); List<T> itemsList(); T firstItem(); boolean isEmpty(); @Override Iterator<T> iterator();  }
@Test public void shouldInterpreteVarargsConstructorAsOrderedListOfItems() { DescribedCollection<String> collection = new DescribedCollection<String>(RepositoryName.from("repository"), "1", "2"); Collection<String> collectionItems = collection.itemsList(); assertThat(collectionItems).isInstanceOf(List.class); }
@Test public void shouldReturnImmutableCollectionAsListIfCreatedFromList() { DescribedCollection<String> collection = new DescribedCollection<String>(RepositoryName.from("repository"), Arrays.asList("1")); List<String> collectionItems = collection.itemsList(); catchException(collectionItems).add("2"); assertThat(caughtException()).isInstanceOf(UnsupportedOperationException.class); }
@Test public void shouldFailWhenTryingToGetIncompatibleCollectionAsList() { DescribedCollection<String> collection = new DescribedCollection<String>(RepositoryName.from("repository"), new HashSet<String>(Arrays.asList("1"))); catchException(collection).itemsList(); assertThat(caughtException()).isInstanceOf(IllegalStateException.class); }