我正在研究一個需要從服務器上拉下並解析.html頁面然後解析它的內容的項目。我搜索了一個字符串作爲單元測試的兩個值,然後將它們保存到List中,然後將它們與手動創建的String []進行比較。代碼如下:列表數組錯誤?
SiteGrabber.java:
//some imports
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class SiteGrabber {
//constructor and java.net stuff
public List<String> getWords(String content){
int prev = 0;
List<String> res = new ArrayList<String>();
String tar = "<tr> <td></td><td><li>";
int tarlen = tar.length();
while(content.indexOf(tar, prev) != -1){
int contentind = content.indexOf("</li>", prev);
if(contentind != -1){
res.add(
content.substring(
content.indexOf(tar, prev) + tarlen,
content.indexOf("</li>", content.indexOf(tar, prev))));
prev = contentind + 5;
}
else{break;}
}
return res;
}
}
SiteGrabberTest.java:
import java.util.List;
import org.junit.Test;
import junit.framework.Assert;
public class SiteGrabberTest {
String htsTest="<tr> <td>List of scrambled words: </td> <td><li>nielle</li></td> </tr><tr> <td></td><td><li>ierneb</li></td> </tr>";
//I want the text between the </td><td><li>...</li> tags.
//2 working tests that show that it sets the List.size() to 0 on a dummy string
//and that it records the right number of results in the List on a valid input.
@Test public void ValidContentTest(){
SiteGrabber myGrabber = new SiteGrabber();
List<String> mylst = myGrabber.getWords(htsTest);
String[] expected = new String[] {"nielle", "ierneb"};
Assert.assertEquals("wrong size", expected.length, mylst.size());
for (int i = 0; i < expected.length; i++) {
Assert.assertEquals("wrong word", expected[i], mylst.get(i));
//breaks on 1st iteration, saying it expects "nielle" and got
//">ierneb", implying some sort of off-by-one error.
}
}
}
而問題是....?請解釋你的問題是什麼。不要讓人們閱讀,編譯和運行你的代碼,只是爲了弄清楚什麼是錯的。 – duffymo 2010-01-17 04:21:13
你忘了告訴錯誤本身。你知道,一個錯誤/異常詳細說明了問題的根本原因。你也知道,一旦問題的根本原因被理解,解決方案是顯而易見的:) – BalusC 2010-01-17 04:21:31
對不起。問題是JUnit在第三個測試ValidContentTest()上失敗。它返回'> ierneb'而不是nielle。我會嘗試刪除一些不需要的部分,並添加JUnit錯誤消息。 – pagboy 2010-01-17 04:24:24