我想为一个使用CompletableFuture.supplyAsync
处理一些数据然后保存到数据库的公共方法编写JUnit测试。然而,传递的supplier方法包含一个私有方法,该方法包含处理和保存数据到数据库的主要逻辑。我想在测试父公共方法的过程中测试这个私有方法。我不知道如何进行。
下面是示例代码:
public void updateGrowthOverviewData(int startId, int endId){
int limit = 10;
int currentStartId = startId;
List<CompletableFuture<Boolean>> futureList = new ArrayList<>();
while (currentStartId <= endId) {
long currentEndId = currentStartId + limit - 1;
long finalCurrentStartId = currentStartId;
futureList.add(this.getFuture(() -> {
try {
return processGrowthOverviewData(finalCurrentStartId, currentEndId);
} catch (Exception ex) {
log.error("Exception in updateGrowthOverviewData | while fetching data for updateGrowthOverviewData | startId : {}, endId : {} | Exception: {}", finalCurrentStartId, currentEndId, ex.getStackTrace());
return false;
}
}));
currentStartId += limit;
}
futureList.forEach(obj -> {
try {
log.info("in updateGrowthOverviewData| value: {}", obj.get());
} catch (InterruptedException | ExecutionException ex) {
log.error("Exception | in updateGrowthOverviewData | while fetching data from Future Object | Exception {}", ExceptionUtils.getStackTrace(ex));
}
});
}
private Boolean processGrowthOverviewData(int startId, int endId){
// code for processing data and saving it into the db -> includes several other private methods -> for better code readability
return true;
}
private <T> CompletableFuture<T> getFuture(Supplier<T> supplier) {
return CompletableFuture.supplyAsync(supplier, this.serviceExecutor);
}
字符串
我不想通过使this.getFuture()
成为受保护的方法来模拟它,因为我将无法测试为更好的代码可读性而创建的私有方法。请帮助我如何测试方法updateGrowthOverviewData
。我是编写UT的新手。
1条答案
按热度按时间xesrikrc1#
一般来说,你的UT应该只写在你的公共方法上。如果这些公共方法调用了一个私有方法,你也会得到私有方法的覆盖。考虑这个代码作为一个例子,我有一个方法,它从较大的数字中减去较小的数字。它调用一个私有方法来确定操作数的正确顺序。
字符串
我们不直接测试私有方法,而是编写测试用例来覆盖私有方法的条件。这里有三个可能的条件:left > right,right > left,left == right。第一个条件将返回true,后两个将返回false。
这两种方法都将包含在一个测试中,看起来像这样:
型