SqlPartIterator implements Iterator<SqlPart> { @Override public SqlPart next() { if (mLastReturned == null) { mLastReturned = mFirst; return mFirst; } SqlPart next = mLastReturned.previous(); if (next == null) { throw new NoSuchElementException("No previous SqlPart."); } mLastReturned = next; return mLastReturned; } SqlPartIterator(@NotNull final SqlPart first); @Override boolean hasNext(); @Override SqlPart next(); @Override void remove();  }
@Test public void immediateNext_returnsFirstItem() { SqlPart sqlPart = mock(SqlPart.class); SqlPartIterator iterator = new SqlPartIterator(sqlPart); SqlPart result = iterator.next(); assertThat(result, is(sqlPart)); }
@Test(expected = NoSuchElementException.class) public void nextWhenThereIsNoNext_throwsException() { SqlPartIterator iterator = new SqlPartIterator(mock(SqlPart.class)); iterator.next(); iterator.next(); }
@Test public void nextWhenThereIsANext_returnsProperItem() { SqlPart first = mock(SqlPart.class); SqlPart second = mock(SqlPart.class); when(first.previous()).thenReturn(second); SqlPartIterator iterator = new SqlPartIterator(first); iterator.next(); SqlPart result = iterator.next(); assertThat(result, is(second)); }