如何测试JAVA异常
测试Java异常的方法
使用JUnit的@Test注解和expected参数
在JUnit 4中,可以通过@Test注解的expected参数指定期望抛出的异常类型。测试通过的条件是方法确实抛出了指定类型的异常。
@Test(expected = IllegalArgumentException.class)
public void testException() {
methodThatThrowsException();
}
使用JUnit 5的assertThrows
JUnit 5引入了assertThrows方法,可以更灵活地捕获异常并验证异常信息。

@Test
public void testException() {
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
methodThatThrowsException();
});
assertEquals("Invalid argument", exception.getMessage());
}
使用try-catch块手动验证
在某些情况下,可能需要手动捕获异常并进行验证。
@Test
public void testException() {
try {
methodThatThrowsException();
fail("Expected exception not thrown");
} catch (IllegalArgumentException e) {
assertEquals("Invalid argument", e.getMessage());
}
}
使用Mockito模拟异常
当测试依赖外部服务的代码时,可以使用Mockito模拟异常抛出。

@Test
public void testException() {
when(mockService.someMethod()).thenThrow(new RuntimeException("Error"));
assertThrows(RuntimeException.class, () -> {
testClass.methodUnderTest();
});
}
验证异常链
有时需要验证异常的起因或嵌套异常。
@Test
public void testExceptionChain() {
Exception exception = assertThrows(RuntimeException.class, () -> {
methodThatThrowsException();
});
assertTrue(exception.getCause() instanceof IOException);
}
使用自定义断言
对于复杂的异常验证,可以创建自定义断言方法。
private void assertException(Class<? extends Exception> expected, Executable executable, String message) {
Exception exception = assertThrows(expected, executable);
assertEquals(message, exception.getMessage());
}






