1

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.

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.