2012-07-11 15 views
7

我有代碼,我檢查JUnit中的異常。我想知道以下哪些是一個很好的JUnit的做法呢?這是更好的,或者的ExpectedException @Test(預期=

首先

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

@Test 
public void checkNullObject() throws CustomException { 
    exception.expect(CustomException.class); 
    MyClass myClass= null; 
    MyCustomClass.get(null); 
} 

@Test(expected=CustomException.class) 
public void checkNullObject() throws CustomException { 
    MyClass myClass= null; 
    MyCustomClass.get(null);  
} 

編輯:請注意CustomException是未經檢查的自定義異常。 (雖然它不會對這個問題產生任何影響)。

+0

我使用第二種形式。 – 2012-07-11 06:05:34

+0

我們也使用第二種形式。 – SWoeste 2012-07-11 06:12:28

+1

重複的http://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit或主要基於意見 – Raedwald 2015-12-18 19:58:55

回答

10

這取決於你想檢查異常。如果你正在做的是檢查的異常被拋出,然後使用@Test(expected=...)可能是最簡單的方法:

@Test(expected=CustomException.class) 
public void checkNullObject() throws CustomException { 
    MyClass myClass= null; 
    MyCustomClass.get(null); 
} 

然而,@rule的ExpectedException有很多更多的選擇,包括檢查的消息,從javadoc

// These tests all pass. 
public static class HasExpectedException { 
    @Rule 
    public ExpectedException thrown= ExpectedException.none(); 

    @Test 
    public void throwsNothing() { 
     // no exception expected, none thrown: passes. 
    } 

    @Test 
    public void throwsNullPointerException() { 
     thrown.expect(NullPointerException.class); 
     throw new NullPointerException(); 
    } 

    @Test 
    public void throwsNullPointerExceptionWithMessage() { 
     thrown.expect(NullPointerException.class); 
     thrown.expectMessage("happened?"); 
     thrown.expectMessage(startsWith("What")); 
     throw new NullPointerException("What happened?"); 
    } 

    @Test 
    public void throwsIllegalArgumentExceptionWithMessageAndCause() { 
     NullPointerException expectedCause = new NullPointerException(); 
     thrown.expect(IllegalArgumentException.class); 
     thrown.expectMessage("What"); 
     thrown.expectCause(is(expectedCause)); 
     throw new IllegalArgumentException("What happened?", cause); 
    } 
} 

因此,您可以檢查消息,異常的原因。爲了檢查信息,你可以使用匹配器,所以你可以檢查startsWith()和類似的。

使用舊式(Junit 3)throw/catch的一個原因是如果您有特定要求。這些並不多,但它可能發生:

@Test 
public void testMe() { 
    try { 
     Integer.parseInt("foobar"); 
     fail("expected Exception here"); 
    } catch (Exception e) { 
     // OK 
    } 
} 
1

第二個版本絕對是標準的做法。老學校的方式來做到這一點,之前JUnit 4中看上去像:

try { 
    codeThatShouldThrowException(); 
    fail("should throw exception"); 
} catch (ExpectedException expected) { 
    //Expected 
} 

有時你可能想,如果你想斷言一些有關異常的消息恢復到這樣,例如。

+0

我認爲即使我們想要檢查有關異常消息的東西,我們可以使用[這種方式](http://stackoverflow.com/questions/11413922/check-errorcode-with-rule-in-junit)。不需要使用這個try -fail-catch結構 – 2012-07-11 06:36:24

相關問題