2013-03-05 120 views
70

我真的很陌生。JUnit測試例外

我正在構造函數上運行一些JUnit測試。構造函數是這樣的,如果給它的一個參數賦予一個null或一個空字符串,它應該會拋出一個異常。

當我在JUnit中用一個空或空字符串參數測試這個構造函數時,我得到一個紅色的條,即使我幾乎100%確定構造函數方法在傳入這些參數時確實會拋出一個異常到它。

如果該方法拋出異常的方式應該不會出現JUnit中的綠色條?或者,當拋出異常的方式按照它應該的方式工作時,你應該得到一個紅色的條?

回答

108
@Test(expected = Exception.class) 

告訴Junit異常是預期的結果,因此當引發異常時測試將被傳遞(標記爲綠色)。

對於

@Test 

爲失敗,如果拋出異常JUnit會考慮測試。
This link may help。

38

你確定你告訴它期待異常嗎?

較新的JUnit(> = 4.7),你可以使用類似(從here

@Rule 
public ExpectedException exception = ExpectedException.none(); 

@Test 
public void testRodneCisloRok(){ 
    exception.expect(IllegalArgumentException.class); 
    exception.expectMessage("error1"); 
    new RodneCislo("891415",dopocitej("891415")); 
} 

,併爲老年人junit的做法是:

​​
+0

如果測試類引發異常,則可以簡單地引發異常並測試已寫入Junit測試用例的位置。使用@Test(expected = IllegalArgumentException.class) – 2015-11-03 07:20:44

5

如果你的構造函數與此類似一個:

public Example(String example) { 
    if (example == null) { 
     throw new NullPointerException(); 
    } 
    //do fun things with valid example here 
} 

然後,當你運行這個JUnit測試時,你會得到一個綠色的條:

@Test(expected = NullPointerException.class) 
public void constructorShouldThrowNullPointerException() { 
    Example example = new Example(null); 
} 
6

使用ExpectedException Rule(版本4.7)的一個優點是您可以測試異常消息,而不僅僅是預期的異常。

而且使用匹配器,你可以測試消息的一部分,你有興趣:

exception.expectMessage(containsString("income: -1000.0")); 
4

雖然@Test(expected = MyException.class)ExpectedException rule是非常不錯的選擇,也有一些情況,其中JUnit3風格異常捕獲仍是最好的路要走:

@Test public void yourTest() { 
    try { 
    systemUnderTest.doStuff(); 
    fail("MyException expected."); 
    } catch (MyException expected) { 

    // Though the ExpectedException rule lets you write matchers about 
    // exceptions, it is sometimes useful to inspect the object directly. 

    assertEquals(1301, expected.getMyErrorCode()); 
    } 

    // In both @Test(expected=...) and ExpectedException code, the 
    // exception-throwing line will be the last executed line, because Java will 
    // still traverse the call stack until it reaches a try block--which will be 
    // inside the JUnit framework in those cases. The only way to prevent this 
    // behavior is to use your own try block. 

    // This is especially useful to test the state of the system after the 
    // exception is caught. 

    assertTrue(systemUnderTest.isInErrorState()); 
} 

另一個聲稱在這裏幫助的圖書館是catch-exception;然而,截至2014年5月,該項目似乎處於維護模式(由Java 8廢棄),很像Mockito catch-exception只能操作非final方法。