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

2eafrhcq  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(207)

我想为一个使用CompletableFuture.supplyAsync处理一些数据然后保存到数据库的公共方法编写JUnit测试。然而,传递的supplier方法包含一个私有方法,该方法包含处理和保存数据到数据库的主要逻辑。我想在测试父公共方法的过程中测试这个私有方法。我不知道如何进行。
下面是示例代码:

  1. public void updateGrowthOverviewData(int startId, int endId){
  2. int limit = 10;
  3. int currentStartId = startId;
  4. List<CompletableFuture<Boolean>> futureList = new ArrayList<>();
  5. while (currentStartId <= endId) {
  6. long currentEndId = currentStartId + limit - 1;
  7. long finalCurrentStartId = currentStartId;
  8. futureList.add(this.getFuture(() -> {
  9. try {
  10. return processGrowthOverviewData(finalCurrentStartId, currentEndId);
  11. } catch (Exception ex) {
  12. log.error("Exception in updateGrowthOverviewData | while fetching data for updateGrowthOverviewData | startId : {}, endId : {} | Exception: {}", finalCurrentStartId, currentEndId, ex.getStackTrace());
  13. return false;
  14. }
  15. }));
  16. currentStartId += limit;
  17. }
  18. futureList.forEach(obj -> {
  19. try {
  20. log.info("in updateGrowthOverviewData| value: {}", obj.get());
  21. } catch (InterruptedException | ExecutionException ex) {
  22. log.error("Exception | in updateGrowthOverviewData | while fetching data from Future Object | Exception {}", ExceptionUtils.getStackTrace(ex));
  23. }
  24. });
  25. }
  26. private Boolean processGrowthOverviewData(int startId, int endId){
  27. // code for processing data and saving it into the db -> includes several other private methods -> for better code readability
  28. return true;
  29. }
  30. private <T> CompletableFuture<T> getFuture(Supplier<T> supplier) {
  31. return CompletableFuture.supplyAsync(supplier, this.serviceExecutor);
  32. }

字符串
我不想通过使this.getFuture()成为受保护的方法来模拟它,因为我将无法测试为更好的代码可读性而创建的私有方法。请帮助我如何测试方法updateGrowthOverviewData。我是编写UT的新手。

xesrikrc

xesrikrc1#

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

  1. public int subtractFromGreaterOfTwo(int left, int right) {
  2. if (gt(left, right)) {
  3. return left - right;
  4. } else {
  5. return right - left;
  6. }
  7. }
  8. private boolean gt(int left, int right) {
  9. return left > right;
  10. }

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

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

展开查看全部

相关问题