You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让同一Mock对象的多次方法调用返回不同值以测试while循环逻辑

单元测试while循环逻辑的解决方案

核心实现原理

Mockito 提供的链式返回功能支持为同一个Mock方法的多次调用指定不同返回值,调用时会按照你传入返回值的顺序依次返回,最后一个返回值会作为后续所有调用的默认返回值,刚好可以解决你遇到的死循环问题。

修正后的测试代码

@Test
public void checkout() {
    // 构造第一次调用返回的非空集合,触发进入循环
    List<Cereal> nonEmptyCerealList = new ArrayList<>();
    nonEmptyCerealList.add(new Cereal());
    // 构造第二次及之后调用返回的空集合,触发退出循环
    List<Cereal> emptyCerealList = new ArrayList<>();

    // 为getList方法按调用顺序指定返回值
    when(groceryListDao.getList(anyString(), anyString()))
        .thenReturn(nonEmptyCerealList, emptyCerealList);

    // 执行待测试方法
    groceryService.checkOut("10", "A5ALV350IIXL");

    // 验证循环内的total方法被调用1次,修正了原代码中times(1)的括号位置错误
    verify(groceryListDao, times(1)).total();
}

多轮循环测试扩展

如果需要验证循环执行N次的逻辑,只需要按顺序传入N个非空集合,最后追加1个空集合即可,示例为验证循环执行3次的写法:

// 前3次调用返回非空集合,第4次及之后返回空集合
when(groceryListDao.getList(anyString(), anyString()))
    .thenReturn(nonEmptyCerealList, nonEmptyCerealList, nonEmptyCerealList, emptyCerealList);
// 验证total方法被调用3次
verify(groceryListDao, times(3)).total();

内容的提问来源于stack exchange,提问作者Brandon Hu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:15:03