2012-07-11 4 views
7

내가 JUnit을에서 예외를 확인 코드가 있습니다. 나는 좋은 JUnit을 연습 인 다음의 어느 알고 싶어?가 (예상 =

먼저

@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

두 번째 양식을 사용합니다. –

+0

두 번째 형식도 사용합니다. – SWoeste

+1

http://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit 또는 주로 의견 기반의 사본 – Raedwald

답변

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); 
    } 
} 

따라서 예외의 원래 원인 인 메시지를 확인할 수 있습니다. 메시지를 확인하려면 matcher를 사용할 수 있으므로 startsWith() 등을 확인할 수 있습니다.

특정 요구 사항이있는 경우 이전 스타일 (Junit 3) throw/catch를 사용하는 한 가지 이유가 있습니다. 이 중 많은 수가 없지만 발생할 수 있습니다.

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

두 번째 버전은 분명히 표준 방법입니다.

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

때때로 당신이 예외 메시지에 대해 뭔가를 주장 할 경우, 예를 들어,이 방법에 복귀 할 수 있습니다 : JUnit 4에서는이처럼 보였다 전에 오래된 학교 방법은 그것을 할 수 있습니다.

+0

우리가 원한다고 생각합니다. 예외 메시지에 대한 내용을 확인하고 [이 방법] (http://stackoverflow.com/questions/11413922/check-errorcode-with-rule-in-junit)으로 갈 수 있습니다. 이 try -fail-catch 구문을 사용할 필요가 없습니다. –

관련 문제