如何告诉 IntelliJ 进行“完整”路径覆盖扫描?

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

假设我有以下代码:

class NetPay {

  /**
   * Computes the net pay of an employee given certain conditions.
   * @param hours - the number of hours worked.
   * @param rate - the hourly rate.
   * @param vacation - whether the employee is on vacation.
   * @param stateTax - whether the employee is subject to state tax.
   * @param federalTax - whether the employee is subject to federal tax.
   * @return the net pay.
   */
  static double computeNetPay(double hours, double rate, boolean vacation,
                              boolean stateTax, boolean federalTax) {
    double grossPay = hours * rate;
    if (vacation) {
      grossPay *= 2;
    }
    if (stateTax) {
      grossPay *= 0.85;
    }
    if (federalTax) {
      grossPay *= 0.80;
    }
    return grossPay;
  }
}

如果我有以下测试,IntelliJ 在其代码和分支覆盖率报告中表示测试覆盖了 100% 的分支,但事实并非如此。我们缺少五个来解释所有八种可能的结果。这些都被注释掉了。

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;

class NetPayTester {

  @Test
  void testComputeNetPay() {
    assertEquals(300, NetPay.computeNetPay(20, 15, false, false, false));
    assertEquals(204, NetPay.computeNetPay(20, 15, false, true, true));
    assertEquals(600, NetPay.computeNetPay(20, 15, true, false, false));
//    assertEquals(240, NetPay.computeNetPay(20, 15, false, false, true));
//    assertEquals(255, NetPay.computeNetPay(20, 15, false, true, false));
//    assertEquals(480, NetPay.computeNetPay(20, 15, true, false, true));
//    assertEquals(510, NetPay.computeNetPay(20, 15, true, true, false));
//    assertEquals(408, NetPay.computeNetPay(20, 15, true, true, true));
  }
}

我的问题是:我如何告诉 IntelliJ 考虑这种路径覆盖?

java unit-testing intellij-idea code-coverage test-coverage
1个回答
0
投票

简短回答:您无法告诉 IntelliJ 计算路径覆盖率。


关于路径覆盖率计算的更多思考:

我不知道有什么工具可以为 Java(也不适用于其他语言)提供路径覆盖率的自动测量。

文章什么是路径覆盖测试?软件测试中重要吗? 描述了手动计算测试路径覆盖率的步骤 - 并且有很多步骤。

文章有这样的说法:

工具的使用

要管理复杂代码的测试用例的创建和执行,请使用自动化测试工具和测试用例生成工具。

没有提及自动测量...

也许您可以获得一些子步骤的帮助,例如计算圈复杂度。

您还会发现以下声明:

虽然理论上实现 100% 路径覆盖是彻底测试的理想目标,但实际上这可能非常困难且耗费资源,特别是对于复杂的软件系统。

由于有如此多的潜在路径和大量的测试要做,因此在许多现实情况下实现 100% 路径覆盖可能并不可行。

因此,我建议您阅读这篇文章,为您的简单示例手动计算路径覆盖率(请记住,如果您添加一个简单的循环,它会变得更加复杂!),然后将路径覆盖率放入您的工具包中,将其埋葬内心深处希望你在现实生活中永远不需要它。

© www.soinside.com 2019 - 2024. All rights reserved.