【发布时间】: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 ;
}
【问题讨论】: