我正在为我的CS课程做一些练习,他们正在给我们进行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
}
}
您“期望”而“事实”落后。
http://junit.sourceforge.net/javadoc/org/junit/Assert.html
assertEquals的第一个参数是EXPECTED,第二个是ACTUAL。
您看到的错误显然是在此行上触发: assertEquals(check.getValue(), 459133821L);
您需要交换期望值和实际值,然后再修正您的计算。如果您尝试获取459133821L,您仍然会得到错误的答案。我没有仔细检查您的所有代码,但是这些测试向您展示了输入输出以及为您提供正确答案的原因。弄清楚为什么要尝试打入459133821L testRemoveDuplicates
(乍一看似乎使用了随机变量,所以我不确定您如何知道期望值),然后您将解决该问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句