【问题标题】:Unit Testing for Code Coverage of Lambda Expression ConditionLambda 表达式条件代码覆盖率的单元测试
【发布时间】:2017-03-01 05:08:28
【问题描述】:

我正在使用 SonarQube 进行静态代码分析,它引发了一个问题,即无法检查第三方库的 if 条件的替代条件:

CountDownLatch connectedSignal = new CountDownLatch(1);
zookeeper = new ZooKeeper(connectionString,this.sessionTimeout, event -> {
if (event.getState() == KeeperState.SyncConnected) {
      connectedSignal.countDown();
}});

connectedSignal.await();

Sonarqube 的错误: “单元测试需要覆盖更多分支才能达到 65.0% 分支覆盖率的最低阈值。”这是因为我没有涵盖单元测试用例中的否定 if 条件。问题是,如何在我的单元测试用例中针对上述 if 条件生成一个否定测试用例?

【问题讨论】:

    标签: java unit-testing lambda


    【解决方案1】:

    通过将 keeperstate 传递给方法并从方法外部设置不同的 keeperstate 来测试是否为负 if 条件来解决。

    public ZooKeeper connect(String connectionString, 
            String sessionTimeout, KeeperState keeperState) {
            zookeeper = new ZooKeeper(connectionString,sessionTimeout, event -> {
                     if (event.getState() == keeperState) {
                        connectedSignal.countDown();
                     }
                  }
            );
    
            connectedSignal.await(this.sessionTimeout, TimeUnit.MILLISECONDS);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2010-10-14
      • 2023-04-07
      • 1970-01-01
      • 2013-04-16
      相关资源
      最近更新 更多