[英]How to run junit tests on a method that returns void?
我無法更改需要測試的方法的簽名 。 測試代碼如下所示
Parser test = new Parser(props);
ArrayList<HDocument> list = new ArrayList<HDocument>();
test.parse("/users/mac/test.xml", list);
System.out.println("Size of list: "+list.size());
assertEquals(5, list.size());
parse
方法簽名如下
public void parse(String filename, Collection<HDocument> docs)
解析方法運行良好,但是當我運行測試儀時,列表大小始終為0。我無法更改解析方法簽名。 我該怎么辦?
這是解析器類,
class Parser{
private Collection<HDocument> docs;
public void parse(String filename, Collection<HDocument> docs) {
docs = new ArrayList<HDocument>();
Collection<HDocument> docsFromXml = new ArrayList<HDocument>();
Handler hl = new Handler();
try {
docsFromXml = hl.getDocs(filename);
} catch (Exception e) {
e.printStackTrace();
}
docs = docsFromXml;
System.out.println("Size:"
+ docs.size()); // This prints the size correctly
}
}
}
如果應該使用parse
將結果添加到docs
集合中,並且在運行parse
方法之后docs
的大小為零,則您的測試將告訴您該parse
已損壞,或者您將其稱為錯誤。 那就是測試應該做的:告訴您某些事情不起作用。
簡而言之:您正在測試parse
正確,並且您的測試正確地告訴您其他錯誤。 您的測試還不錯; parse
肯定某種程度上是錯誤的。 (也許您應該問StackOverflow的問題是如何解決您的parse
方法。)
錯誤是解析方法本身。
public void parse(String filename, Collection<HDocument> docs) {
docs = new ArrayList<HDocument>(); /* First problem here: The method should add values to the parameter not to a new List-Instance */
[...]
docs = docsFromXml; // second error here. you overwrite the list again.
應該是這樣的:
public void parse(String filename, Collection<HDocument> docs) {
if(docs==null) throw new IllegalArgumentException("no list for adding values specified");
if(filename==null) throw new IllegalArgumentException("no filename specified");
Handler hl = new Handler();
try {
docs.addAll(hl.getDocs(filename));
} catch (Exception e) {
throw new RuntimeEception(e); // never sink exception without proper handling
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.