【发布时间】:2022-01-27 21:38:46
【问题描述】:
我正在尝试模拟一个非常简单的代码行,该代码行用于使用 Java 查询 DynamoDB。这是查询的一些示例代码 -
List<Pojo> result;
try {
if (filters == null) {
this.queryExpression = new DynamoDBQueryExpression<Pojo>()
.withKeyConditionExpression(partitionKeyCondition)
.withExpressionAttributeValues(this.eav);
} else {
setFilterQueryExpression(filters);
}
result = this.dynamoDBMapper.query(Pojo.class, queryExpression);
} catch (final Exception e) {
throw new InternalServerException("Something went wrong with the database query: ", e);
}
上面的代码有效,我可以检索自动反序列化到 Pojo 中的行列表。
我现在正尝试按如下方式模拟 this.dynamoDBMapper.query 调用 -
@Mock
private DynamoDBMapper mapper;
List<Pojo> result = new ArrayList<>();
when(mapper.query(Pojo.class,Mockito.any(DynamoDBQueryExpression.class)).thenReturn(result);
我无法做到这一点,但出现错误 -
Cannot resolve method 'thenReturn(java.util.List<com.amazon.xxx.xxx.Pojo>)'
我也尝试了另一种方法-
doReturn(result).when(mapper).query(Pojo.class, Mockito.any(DynamoDBQueryExpression.class));
这似乎可以编译,但测试失败并出现错误 -
org.mockito.exceptions.misusing.WrongTypeOfReturnValue
我查看了查询的预期输出类型为 PaginatedQueryList 的其他示例,我也尝试更改为该示例。但是我仍然不确定为什么上面会抛出错误。
【问题讨论】:
-
您是否尝试过将 List
更改为 PaginatedQueryList 或类似的?根据文档,查询方法返回 List 的特定实现。您可以将特定实现分配给更通用的 List 变量,但不能返回更通用的类型,其中每个签名都请求特定实现。因此,Mockito 无法解析您要求的方法。 -
我确实尝试将返回类型从
List更改为PaginatedQueryList,但when仍然不接受它。它说Cannot resolve method 'thenReturn(PaginatedQueryList<Pojo>)'。我觉得我需要做一些额外的事情才能让它发挥作用,但我不完全确定如何。
标签: java amazon-web-services mockito amazon-dynamodb dynamodb-mapper