【问题标题】:How to know what instructions I did/didn't execute at the end of my test in JUnit如何知道我在 JUnit 中的测试结束时执行/未执行的指令
【发布时间】:2022-01-25 16:54:47
【问题描述】:

我是一名不错的 Java 开发人员,但我对测试框架了解不多。我刚刚创建了一个简单的方法:

public static String signOf(String str) {//expects a number as String and gives you the sing of it (positive or negative)
    int number = 0;
    str = str.trim();
    try {
        number = Integer.parseInt(str);
    } catch (Exception e) {
        return "NaN";
    }

    if (str.equals("0")) {
        return "positive and negative";
    }
    if(str.length()==count(number)){
            return "positive";
    }
    if(str.length()==(count(number)+1)){
        if (str.charAt(0) == '+') {
            return "positive";
        }
        if (str.charAt(0) == '-') {
            return "negative";
        }
    }
     return "NaN" ;
}

为了测试它,我创建了另一种方法(我使用 IntelliJ 作为 IDE):

@Test
public void testSignOf(){
    assertEquals("positive and negative",signOf("0"),"0 is positive and negative at the same time.");

    assertEquals("positive",signOf("19"),"19 is positive.");

    assertEquals("negative",signOf("-0"),"-0 is negative.");
    assertEquals("positive",signOf("+0"),"+0 is positive.");

    assertEquals("negative",signOf("-12"),"-12 is negative.");
    assertEquals("positive",signOf("+23"),"+23 is positive.");

    assertEquals("NaN",signOf("1-1"),"1-1 is NaN.");
    assertEquals("NaN",signOf("ad"),"ad is NaN.");
    assertEquals("NaN",signOf("-"),"- is NaN.");
    assertEquals("NaN",signOf("+"),"+ is NaN.");
    assertEquals("NaN",signOf("+-"),"+- is NaN.");
    assertEquals("NaN",signOf("--1"),"--1 is NaN.");
}

有什么方法可以知道我的测试是否输入了我的代码的每条指令以及所有可能的情况。通常在测试结束时,如果一切按预期进行,它会变为绿色。但是,如果您没有确实在 if 语句之后以您测试的方法访问了某个指令,它不会通知您。
这个测试让我想起了这个深刻的想法:

我知道的东西很少。
我知道我不知道的东西很大。
但我不知道我不知道的东西要大得多。


其余代码:

public static int  count(int num){
    if (num==0) return 1;//Btw the test helped me to add this if 
    int count = 0;
    while (num != 0) {
        // num = num/10
        num /= 10;
        ++count;
    }
    return count ;
}

【问题讨论】:

    标签: java junit


    【解决方案1】:

    如果您想知道执行了哪些代码行,那就是代码覆盖工具的用途。 Intelliij 带有一个代码覆盖率插件,您可以使用代码覆盖率运行您的测试,它会告诉您哪些行被覆盖,哪些未被覆盖。见https://www.jetbrains.com/help/idea/running-test-with-coverage.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多