如何知道我在 JUnit 中的测试结束时执行/未执行哪些指令



我是一个不错的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 ;
}

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

最新更新