這取決於你想檢查異常。如果你正在做的是檢查的異常被拋出,然後使用@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
}
}
我使用第二種形式。 – 2012-07-11 06:05:34
我們也使用第二種形式。 – SWoeste 2012-07-11 06:12:28
重複的http://stackoverflow.com/questions/785618/in-java-how-can-i-validate-a-thrown-exception-with-junit或主要基於意見 – Raedwald 2015-12-18 19:58:55