I am trying to unit test a method getFruitItemMap()
which calls another method getAllItemsBelongingToFruit
whose return type is Iterator
in the same class. I am trying to mock this method using Mockito.spy()
, but unsure of how to return an Iterator. I checked other answers on stack overflow here, but looks like I am missing something here.
class FruitItemImpl {
Map<String, Fruit> getFruitItemMap() {
Map<String, Fruit> fruitMap = new HashMap<>();
Iterator<Fruit> items = getAllItemsBelongingToFruit("Apple");
while (items.hasNext()) {
Fruit fruitItem = items.next();
fruitMap.put(fruitItem.getID(), fruitItem);
}
return fruitMap;
}
public Iterator<Fruit> getAllItemsBelongingToFruit(String fruit) {
//some logic that returns an iterator
}
Here is the unit test:
@Test
public void testGetFruitItemMap() {
Map<String, Fruit> fruitItemMap = new HashMap<>();
FruitItemImpl doa1 = Mockito.spy(dao);
Mockito.doReturn(**new Iterator<Fruit>**).when(doa1).getAllItemsBelongingToFruit("Apple") //Here
Assert.assertEquals(fruitItemMap.size(), doa1.getFruitItemMap().size());
}
Since I am new to Mockito and Unit Testing world, trying to get my head around it. I am not sure how to make mockito return an iterator Mockito.doReturn()
in this case.