Skip to content

Instantly share code, notes, and snippets.

@chbatey
Created June 1, 2013 11:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chbatey/5690062 to your computer and use it in GitHub Desktop.
Save chbatey/5690062 to your computer and use it in GitHub Desktop.
public static <T> void mockIterable(Iterable<T> iterable, T... values) {
Iterator<T> mockIterator = mock(Iterator.class);
when(iterable.iterator()).thenReturn(mockIterator);
if (values.length == 0) {
when(mockIterator.hasNext()).thenReturn(false);
return;
} else if (values.length == 1) {
when(mockIterator.hasNext()).thenReturn(true, false);
when(mockIterator.next()).thenReturn(values[0]);
} else {
// build boolean array for hasNext()
Boolean[] hasNextResponses = new Boolean[values.length];
for (int i = 0; i < hasNextResponses.length -1 ; i++) {
hasNextResponses[i] = true;
}
hasNextResponses[hasNextResponses.length - 1] = false;
when(mockIterator.hasNext()).thenReturn(true, hasNextResponses);
T[] valuesMinusTheFirst = Arrays.copyOfRange(values, 1, values.length);
when(mockIterator.next()).thenReturn(values[0], valuesMinusTheFirst);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment