Yogesh D
Yogesh D

Reputation: 1666

How to mock method in the same class that returns an Iterator in java

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.

Upvotes: 1

Views: 466

Answers (1)

Mureinik
Mureinik

Reputation: 311018

The easiest way would be to have a collection of the appropriate Fruit objects, and return an Iterator from it. In your case, you could just return an iterator from the fruitItemMap's values() you're using in your test:

@Test
public void testGetFruitItemMap() {
    Map<String, Fruit> fruitItemMap = new HashMap<>();
    FruitItemImpl doa1 = Mockito.spy(dao);
    Mockito.doReturn(fruitItemMap.values().iterator()) // Here!
           .when(doa1).getAllItemsBelongingToApple("Apple");
    Assert.assertEquals(fruitItemMap.size(), doa1.getFruitItemMap().size());
}

Upvotes: 1

Related Questions