【发布时间】:2021-10-21 22:36:11
【问题描述】:
我有一个我试图模拟的函数,它包含 while 循环形式的递归逻辑,我试图弄清楚如何访问 while 循环的内部而不是永远循环。
//this is supposed to go through all the items in the grocery list given the parameters until the groceries are all checked out
public void checkOut(String maxItems, String code){
List<cereal> groceryList;
groceryList = groceryListDao.getList(String maxItems, String code);
while (!groceryList.isEmpty()){
groceryListDao.total();
//other logic
groceryList = groceryListDao.getList(String maxItems, String code);
}
}
我可以编写一个 junit 测试来验证如果购物清单为空,则永远不会进入 while 循环。但是,我不确定如何编写代码来测试是否进入了while循环,因为我需要模拟groceryListDao.getList不为空以进入while循环,然后为空以退出while循环。我不知道该怎么做。
@Test
public void checkout() {
List<Cereal> cereal = new ArrayList<>();
Cereal x = new Cereal();
cereal.add(x);
when(groceryListDao.getList(anyString(), anyString())).thenReturn(cereal);
groceryService.checkout("10", "A5ALV350IIXL");
verify(groceryListDao, times(1).total());
}
如何验证是否在循环内调用了 total() 而不会卡住?
【问题讨论】:
-
这不是递归的。
checkOut不调用自己。这段代码是如何工作的?如果对getList的第一次调用不是空的,为什么下一个是空的?total是否停止在进一步调用中返回项目? -
(也请发布您的实际代码,因为您发布的内容无法编译)
-
2 种独立的测试方法