夥計們我是JUnit測試的新手,並試圖抓住它,現在我正在爲構造函數編寫JUnit測試(用於創建有向圖的Digraph類),它在讀取時拋出IllegalArgumentException負int值,並且如果一切正常(節點值的數量)大於零,則創建一個圖形。JUnit測試構造函數測試
有向圖類:
In in = new In();
public Digraph(In in) {
try {
this.nodes = in.readInt();
System.out.println("Total nodes in graph: "+ nodes);
if (nodes < 0) throw new IllegalArgumentException("Number of vertices must be > 0);
int E = in.readInt();
if (E < 0) throw new IllegalArgumentException("Number of edges must be >0);
}catch (NoSuchElementException e) {
throw new InputMismatchException("Invalid input format in Digraph constructor");
}
下面是我試圖寫的測試:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test(expected = IllegalArgumentException.class)
public void DigraphIn() {
Digraph G = new Digraph(in.readInt());
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Vertices can't be nagative");
exception.expectMessage("Invalid input format in Digraph constructor");
exception.expectMessage("Number of edges in a Digraph must be nonnegative");
try{
}catch (AssertionError e){
}
}
我應該如何使用一個(或兩個)測試用例測試這兩種情況?如果沒有「in」檢測到的-ve值,我會得到java.lang.AssertionError,否則測試通過。在此先感謝
csoroiu,所以有應該對每個異常進行單獨測試?因爲如果我不這樣做,我會得到AssertionError! – user1569891
@ user1569891我更新了帖子,每個異常都需要一個方法。您可以模擬In類或創建一個爲每個測試返回'Digraph'構造函數所需的值以根據需要執行該測試的值。 – Claudiu
使用'ExpectedException'更好,在這個測試中你不能驗證異常拋出的位置。 – Tobb