使用 assertthrows 方法可以验证异常类型,它接收预期的异常类、执行代码的 executable 接口实现(通常用 lambda 表达式),并返回捕获到的异常实例。调用该方法后,若代码块抛出指定类型的异常则测试通过,否则失败;同时你可以拿到异常对象来检查其消息或属性。

如何获取断言后的异常实例进行详细检查?
在调用 assertThrows 时,它会返回一个异常对象,你可以直接对该对象调用 getMessage() 等方法来验证具体的错误信息或状态。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ExceptionTest {
@Test
public void testExceptionMessage() {
// 定义要执行的代码块
Runnable code = () -> {
throw new IllegalArgumentException("Invalid input");
};
// 捕获异常并验证消息
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
code
);
// 验证异常的具体内容
if (!ex.getMessage().equals("Invalid input")) {
throw new AssertionError("Message mismatch");
}
}
}
如何处理未预期抛出的异常类型?
如果代码块抛出了与预期不同的异常类型,assertThrows 会立即导致测试失败,不会返回任何实例,从而确保只有符合预期的异常路径才会被接受。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class WrongExceptionTest {
@Test
public void testWrongExceptionType() {
Runnable code = () -> {
throw new RuntimeException("Unexpected error");
};
try {
// 期望抛出 IllegalArgumentException,但实际抛出 RuntimeException
assertThrows(IllegalArgumentException.class, code);
fail("Expected an exception to be thrown");
} catch (AssertionError e) {
// 这里会捕获到因为异常类型不匹配而导致的断言失败
System.out.println("Caught expected failure: " + e.getMessage());
}
}
}
基于程序中某个输入、条件或结果的具体问题
当传入的代码块没有抛出任何异常时,assertThrows 也会直接抛出 AssertionError 使测试失败,这保证了必须发生异常才能通过验证。











