[英]How to mock method in the same class that returns an Iterator in java
我正在尝试对一个方法getFruitItemMap()
进行单元测试,该方法调用另一个方法getAllItemsBelongingToFruit
其返回类型是同一类中的Iterator
。 我正在尝试使用Mockito.spy()
模拟此方法,但不确定如何返回迭代器。 我在这里检查了堆栈溢出的其他答案,但看起来我在这里遗漏了一些东西。
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
}
这是单元测试:
@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());
}
由于我是 Mockito 和单元测试世界的新手,因此我试图了解它。 在这种情况下,我不确定如何让 mockito 返回迭代器Mockito.doReturn()
。
最简单的方法是拥有一个合适的Fruit
对象的集合,并从中返回一个Iterator
。 在您的情况下,您可以从您在测试中使用的fruitItemMap
的values()
返回一个迭代器:
@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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.