这取决于您要签入异常的内容。如果您所做的只是检查是否引发异常,那么使用可能是最简单的方法:@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)投掷/接球的一个原因是如果您有特定的要求。这些并不多,但它可能发生:
@Test
public void testMe() {
try {
Integer.parseInt("foobar");
fail("expected Exception here");
} catch (Exception e) {
// OK
}
}