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

使用Mockito的doReturn时持续抛出UnfinishedStubbingException问题求助

解决Mockito doReturn触发UnfinishedStubbingException的问题

你的问题出在Mockito的doReturn().when()语法使用错误,和thenReturn无关,是你没遵循doReturn的正确调用格式,导致Mockito判定存根未完成。

核心错误点

Mockito中doReturn的正确语法是:

doReturn(要返回的模拟对象).when(模拟实例).目标方法(参数匹配器);

你的代码存在两个关键问题:

  1. when()中传入方法调用而非模拟实例:比如doReturn(mockTable).when(dynamoDB.getTable("users"));,这里when()里应该直接放dynamoDB这个mock实例,而非调用它的getTable方法。
  2. 链式方法调用未分步存根:mockTable.getIndex("").query(...)这种链式调用不能直接写在when()后,需要拆分成两步分别存根。

另外业务代码里有个小bug:while循环中用了list.add,但定义的变量是usersList,会导致编译错误,需先修正。

修正后的测试代码

确保dynamoDB是mock实例(不能用真实DynamoDB对象),按正确语法存根:

// 先mock所有依赖对象
DynamoDB dynamoDB = mock(DynamoDB.class);
List<Users> usersList = new ArrayList<>();
Table mockTable = mock(Table.class);
Index mockIndex = mock(Index.class); // 新增mock Index对象,对应getIndex的返回值
Users details = new Users("", "", "");
Item mockItem = mock(Item.class);
ItemCollection<QueryOutcome> mockCollection = mock(ItemCollection.class);
Iterator<Item> mockIterator = mock(Iterator.class);

// 正确的存根写法
doReturn(mockTable).when(dynamoDB).getTable("users");
doReturn(mockIndex).when(mockTable).getIndex("userIndex"); // 匹配业务代码里的索引名"userIndex"
doReturn(mockCollection).when(mockIndex).query(any(QuerySpec.class)); // 用any匹配任意QuerySpec实例
doReturn(mockIterator).when(mockCollection).iterator();
doReturn(true).doReturn(false).when(mockIterator).hasNext();
doReturn(mockItem).when(mockIterator).next();
// 存根Item的toJSONPretty方法,返回可被Util.jsonToObject解析的JSON字符串
doReturn("{\"id\":\"\",\"name\":\"\",\"email\":\"\"}").when(mockItem).toJSONPretty();

// 执行测试
List<Users> result = dynamoService.getUsers("");
assertNotNull(result.get(0));

额外提示

  • 无需mockArrayList这类简单集合,直接用真实实例更省心,除非需要验证add方法的调用次数。
  • 测试时用any(QuerySpec.class)匹配任意QuerySpec实例即可,若需匹配特定实例可改用eq()。
  • 必须mockItem对象并存根toJSONPretty方法,否则Util.jsonToObject会因拿到无效JSON报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:20:30