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

问题描述 投票:0回答:1

我想为一个公共方法编写junit测试,该方法使用CompletableFuture.supplyAsync来处理一些数据,然后将其保存到数据库。但是,传递的供应商方法包含一个私有方法,该方法包含处理数据并将数据保存到数据库的主要逻辑。我想在测试父公共方法的过程中也测试这个私有方法。我不知道如何继续。

这是示例代码:

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 的新手。

spring-boot junit mockito spring-boot-test completable-future
1个回答
0
投票

一般来说,你的 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;
}

我们不直接测试私有方法,而是编写测试用例来覆盖私有方法的条件。这里有三种可能的情况;左>右,右>左,左==右。第一个条件将返回 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)));
}
© www.soinside.com 2019 - 2024. All rights reserved.