PeekIterator implements Iterator<T> { @Override public T next() { if (!hasNext()) { throw (new NoSuchElementException("Iterator has no elements left.")); } T toReturn = nextitem; nextitem = null; return toReturn; } PeekIterator(Iterator<T> iterator); @Override boolean hasNext(); @Override T next(); T peek(); @Override void remove();  }
@Test public void next_ThrowsExceptionWithEmptyList() { PeekIterator<Integer> tested = new PeekIterator<Integer>( emptyList.iterator()); boolean thrown = false; try { tested.next(); } catch (NoSuchElementException e) { thrown = true; } assertTrue(String.format("Exception: %s not thrown", NoSuchElementException.class.getCanonicalName()), thrown); }
@Test public void next_ThrowsExceptionWhenNoElementsAreLeft() { PeekIterator<Integer> tested = new PeekIterator<Integer>( listWithElements.iterator()); boolean thrown = false; tested.next(); tested.next(); tested.next(); try { tested.next(); } catch (NoSuchElementException e) { thrown = true; } assertTrue(String.format("Exception: %s not thrown", NoSuchElementException.class.getCanonicalName()), thrown); }
@Test public void next_ReturnsNextElementsInOrder() { PeekIterator<Integer> tested = new PeekIterator<Integer>( listWithElements.iterator()); assertEquals(listWithElements.get(0), tested.next()); assertEquals(listWithElements.get(1), tested.next()); assertEquals(listWithElements.get(2), tested.next()); }