使用Mockito测试Java版DynamoDB SDK v2 Repository方法报错解决
问题分析与解决方案
错误原因
- 你在
setup方法里重新构建了dynamoDbEnhancedClient和dyamoDbTable,直接覆盖了Mockito创建的mock对象,导致后续的stub配置完全失效。 - 试图mock
Key.builder()这类静态方法调用链,哪怕启用了mock-maker-inline,这种写法也不符合Mockito的规范,而且完全没必要——Key是值对象,直接构造真实实例用于验证即可。 - 测试方法名写错(
testGetDoorState应为testGetCustomer),还有变量名拼写错误(custmer→customer)。
修正后的测试代码
@ExtendWith(MockitoExtension.class) class CustomerRepositoryTest { @Mock private DynamoDbEnhancedClient dynamoDbEnhancedClient; @Mock private DynamoDbTable<Customer> customerTable; // 修正变量名拼写,提升可读性 @InjectMocks private CustomerRepository repository; private final String TABLE_NAME = "Customer"; private final String customerId = "123"; @Test void testGetCustomer() { // 构造测试用的Customer对象 Customer customer = new Customer(); customer.setCustomerId(customerId); customer.setName("name"); // 构造预期的Key实例(无需mock,直接用真实对象) Key expectedKey = Key.builder().partitionValue(customerId).build(); // Stub增强客户端的table方法,返回mock的表对象 when(dynamoDbEnhancedClient.table(TABLE_NAME, TableSchema.fromBean(Customer.class))) .thenReturn(customerTable); // Stub表的getItem方法,传入预期Key时返回测试用Customer when(customerTable.getItem(expectedKey)).thenReturn(customer); // 执行测试并断言结果 Customer result = repository.getCustomer(customerId); assertEquals(customer, result); // 可选:验证mock方法的调用次数,确保逻辑符合预期 verify(dynamoDbEnhancedClient, times(1)) .table(TABLE_NAME, TableSchema.fromBean(Customer.class)); verify(customerTable, times(1)).getItem(expectedKey); } }
关键修正点
- 删除
setup方法中的实例化代码,保留Mockito创建的mock对象,确保@InjectMocks能正确注入到Repository中。 - 移除不必要的
Key和DynamoDbClientmock(当前测试不需要直接操作底层DynamoDbClient)。 - 直接构造真实的Key对象用于stub和验证,规避mock静态方法的问题。
- 修正方法名与变量名的拼写错误。
- 增加
verify验证,确保mock方法按预期被调用,提升测试严谨性。
内容的提问来源于stack exchange,提问作者user15125148
相关产品推荐
相关产品推荐

