简体   繁体   中英

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM