Spring Boot 如何测试CompletableFuture.supplyAsync方法的supplier方法中传递的私有方法?

2eafrhcq  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(95)

我想为一个使用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的新手。

xesrikrc

xesrikrc1#

一般来说,你的UT应该只写在你的公共方法上。如果这些公共方法调用了一个私有方法,你也会得到私有方法的覆盖。考虑这个代码作为一个例子,我有一个方法,它从较大的数字中减去较小的数字。它调用一个私有方法来确定操作数的正确顺序。

public int subtractFromGreaterOfTwo(int left, int right) {
  if (gt(left, right)) {
    return left - right;
  } else {
    return right - left;
  }
}

private boolean gt(int left, int right) {
  return left > right;
}

字符串
我们不直接测试私有方法,而是编写测试用例来覆盖私有方法的条件。这里有三个可能的条件:left > right,right > left,left == right。第一个条件将返回true,后两个将返回false。
这两种方法都将包含在一个测试中,看起来像这样:

@Test
public void testLeftGreater() {
    assertThat(someService.subtractFromGreaterOfTwo(10, 5), is(equalTo(5)));
    assertThat(someService.subtractFromGreaterOfTwo(5, 10), is(equalTo(5)));
    assertThat(someService.subtractFromGreaterOfTwo(10, 10), is(equalTo(0)));
}

相关问题