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

如何使用Mockito模拟DynamoDB的batchSave()失败场景?

模拟DynamoDBMapper.batchSave()失败场景

要让mock的batchSave()返回包含未成功保存对象的FailedBatch列表,你可以按以下步骤实现:

  • 准备模拟失败的实体对象和对应异常
  • 创建并配置FailedBatch实例,关联失败对象与异常
  • 构造包含该FailedBatch的列表,设置为mock方法的返回值

具体代码实现

// 1. 准备要模拟保存失败的实体(替换为你的实际业务实体类)
YourEntity failedItem = new YourEntity();
failedItem.setId("test-failed-id");

// 2. 模拟DynamoDB保存失败的异常(根据测试场景选择对应异常类型)
AmazonServiceException failureException = new ConditionalCheckFailedException("条件检查不通过,保存操作失败");

// 3. 创建并配置FailedBatch实例
DynamoDBMapper.FailedBatch failedBatch = Mockito.mock(DynamoDBMapper.FailedBatch.class);
// 设置未成功保存的对象列表
when(failedBatch.getUnprocessedItems()).thenReturn(List.of(failedItem));
// 设置导致失败的异常
when(failedBatch.getException()).thenReturn(failureException);

// 4. 构造失败批次列表并配置mock
List<DynamoDBMapper.FailedBatch> failedBatches = List.of(failedBatch);
when(mapper.batchSave((Iterable<? extends Object>) any())).thenReturn(failedBatches);

进阶:反射创建FailedBatch(若mock方式受限)

如果FailedBatch因包访问权限无法直接mock,可通过反射实例化:

// 反射获取FailedBatch的构造方法
Constructor<DynamoDBMapper.FailedBatch> constructor = DynamoDBMapper.FailedBatch.class.getDeclaredConstructor(AmazonServiceException.class, List.class);
constructor.setAccessible(true);
// 直接创建FailedBatch实例
DynamoDBMapper.FailedBatch failedBatch = constructor.newInstance(failureException, List.of(failedItem));

// 后续同样构造列表并配置mock
List<DynamoDBMapper.FailedBatch> failedBatches = List.of(failedBatch);
when(mapper.batchSave((Iterable<? extends Object>) any())).thenReturn(failedBatches);

注意事项

  • 可根据测试场景替换异常类型,比如ProvisionedThroughputExceededException(吞吐量超限)、ItemCollectionSizeLimitExceededException(集合大小超限)等
  • 若需模拟多个失败批次,只需创建多个FailedBatch实例加入列表即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:39:55