Reputation: 3267
I have mocked an iterable and added when conditions for iterable.iterator()
and iterable.iterator().next()
and iterable.iterator().hasNext()
.
I can print and see that iterable.iterator()
when called gives me an iterator but hasNext()
seems to be returning false even after mocking it.
Here is how I have mocked the Iterator
and Iterable
// mock iterator
final Iterator mockIterator = Mockito.mock(Iterator.class);
final Iterable mockIterable = Mockito.mock(Iterable.class);
Mockito.when(mockIterator.hasNext()).thenReturn(true, false);
Mockito.when(mockIterator.next()).thenReturn(mockGoogleAdsRow);
Mockito.when(mockIterable.iterator()).thenReturn(mockIterator);
Mockito.when(searchPagedResponse.iterateAll()).thenReturn(mockIterable);
I have this for loop in code which needs to be tested (verified)
// System.out.println("response.iterateAll()" + response.iterateAll());
// This prints --> response.iterateAll()Mock for Iterable, hashCode: 1027306253
// System.out.println("next " + response.iterateAll().iterator().next());
// This prints --> next Mock for GoogleAdsRow, hashCode: -767510433
-------------> HERE THIS PART IS FAILING, HASNEXT
// System.out.println("has next " + response.iterateAll().iterator().hasNext());
// This prints --> has next false
// System.out.println("size " + Iterators.size(response.iterateAll().iterator()));
// This prints size 0
for (final GoogleAdsRow googleAdsRow : response.iterateAll()) {
System.out.println("Inside loop");
Any Help is appreciated
EDIT :
searchPagedResponse
is mocked like this
searchPagedResponse = Mockito.mock(GoogleAdsServiceClient.SearchPagedResponse.class);
mockGoogleAdsRow = Mockito.mock(GoogleAdsRow.class);
Mockito.when(mockGoogleAdsServiceClient.searchPagedCallable()).thenReturn(callable);
Mockito.when(mockGoogleAdsServiceClient.searchPagedCallable().call(searchGoogleAdsRequest)).thenReturn(searchPagedResponse);
Upvotes: 0
Views: 952
Reputation: 3267
I figured easy way to do it was simply doing this, instead of mocking an iterator.
Mockito.when(searchPagedResponse.iterateAll()).thenReturn(Arrays.asList(mockGoogleAdsRow));
Not sure why mocking the iterator was failing, but I have recently started working with Java, so simple things, I have been doing in round about ways.
Upvotes: 1