assertThrows
是 Java 中的一个断言方法,用于测试代码是否抛出了预期的异常。这个方法属于 JUnit 测试框架中的一个重要功能,它允许开发者编写测试用例来验证在特定条件下代码是否会正确地抛出异常。
assertThrows
方法的基本语法如下:
assertThrows(expectedType, executable);
expectedType
是期望抛出的异常类型。executable
是一个执行代码块,可以是 lambda 表达式或方法引用,它应该包含可能抛出异常的代码。assertThrows
主要有两种使用方式:
assertThrows
来确保没有引入新的错误。assertThrows
没有捕获到预期的异常原因:
解决方法:
executable
中的代码确实会抛出预期的异常。import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ExampleTest {
@Test
void testMethodThatShouldThrowException() {
// 正确的使用 assertThrows
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("Expected exception");
});
// 错误的使用,异常被捕获了
try {
throw new IllegalArgumentException("This exception will not be caught by assertThrows");
} catch (IllegalArgumentException e) {
// Exception handled here
}
// assertThrows will fail because no exception was thrown in this scope
assertThrows(IllegalArgumentException.class, () -> {
// No code here to throw an exception
});
}
}
在这个示例中,第一个 assertThrows
调用会成功,因为它确实抛出了一个 IllegalArgumentException
。第二个 assertThrows
调用会失败,因为异常在调用之前已经被捕获并处理了。第三个 assertThrows
调用也会失败,因为没有代码抛出异常。
通过这种方式,开发者可以确保他们的代码在预期的错误条件下能够正确地抛出异常,并且可以通过单元测试来验证这一点。