我正在爲CS課程做一些練習,他們給我們Junit測試,但他們只告訴我們,如果我們失敗或通過。輸出/預期的輸出對我來說很亂。瞭解這些JUnit測試結果
我給以這種方式預期輸出/輸出:
java.lang.AssertionError: expected <3143794514> but was <459133821>
我注意到值< 459133821L>測試的代碼也有發現。不過,我仍然是一個初學者。顯然,adler32是爲了通過校驗和檢查錯誤,但我不知道如何利用它。有沒有辦法讓這個節目更有意義的消息,所以我知道我的代碼出了什麼問題?
例如:我希望計算一個字符串中的所有單詞。這些測試能告訴我哪些輸入/輸出返回了錯誤的答案嗎?
這裏是JUnit類的一個示例:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.io.*;
import java.util.zip.Adler32;
public class TestStringProblems {
private static final int RUNS = 100000;
private static final int SEED = 12345;
private StringProblems sp = new StringProblems();
@Test
public void testCountWords() {
BufferedReader br = null;
Adler32 check = new Adler32();
int count = 0;
try {
br = new BufferedReader(new FileReader("warandpeace.txt"));
String line = br.readLine();
while(line != null) {
int words = sp.countWords(line.trim());
count += words;
check.update(words);
line = br.readLine();
}
} catch(IOException e) { System.out.println("Error: " + e); assertTrue(false); }
finally { try { br.close(); } catch(Exception e) { } }
assertEquals(count, 562491); // number of words in War and Peace
assertEquals(check.getValue(), 2309395892L); // checksum of word counts
}
@Test
public void testRemoveDuplicates() {
Adler32 check = new Adler32();
java.util.Random rng = new java.util.Random(SEED);
for(int i = 0; i < RUNS; i++) {
StringBuilder sb = new StringBuilder();
int len = rng.nextInt(500);
for(int j = 0; j < len; j++) {
char c = (char)(1 + rng.nextInt(50000));
int rep = rng.nextInt(10) + 1;
for(int k = 0; k < rep; k++) {
sb.append(c);
}
}
check.update(sp.removeDuplicates(sb.toString()).getBytes());
}
assertEquals(check.getValue(), 459133821L);
}
}
感謝。
public class StringProblems {
public String removeDuplicates(String s) {
String newStr = "";
if (s.length() == 0) {
return s;
}
int length = s.length() - 1;
for(int i = 0;i<length+1;i++) {
if(i!=0 && s.charAt(i)!=s.charAt(i-1)) {
newStr += s.charAt(i);
}
}
return s.charAt(0) + newStr;
}
public int countWords(String s) {
String newStr = s.trim(); // removes unnecessary whitespace
if (newStr.isEmpty()) {
return 0;
}
return newStr.split("\\W+").length; // should work since it creates an array of substrings,
// length should indicate how many substrings are in the new string
}
}
你可以顯示你的實際代碼失敗嗎? – nhouser9
我的評論是OT,但我傾向於告訴測試的作者在斷言中編寫適當的JavaDoc和字符串。在這種情況下,JavaDoc將是解釋隨機數如何在測試中發揮作用的好地方。順便說一下,斷言的所有實現(包括內置關鍵字)都支持在出現故障時打印的描述字符串。在單元測試中捕捉任何錯誤也是一個非常糟糕的主意。他們應該拋出異常而不是捕捉它們。 –
添加了我的失敗代碼。 – BodyBingers