2021年3月25日星期四

iterable.iterator().hasNext() returning false after mocking behaviour

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);  
https://stackoverflow.com/questions/66811094/iterable-iterator-hasnext-returning-false-after-mocking-behaviour March 26, 2021 at 12:35PM

没有评论:

发表评论