예외 상황을 확인하려는 대상에 따라 다릅니다. 당신은 예외가 다음 @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
}
}
두 번째 양식을 사용합니다. –
두 번째 형식도 사용합니다. – SWoeste
http://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit 또는 주로 의견 기반의 사본 – Raedwald