使用 assertthrows() 方法捕获异常对象,并直接调用其 getmessage() 方法验证消息内容。该方法返回具体的异常实例,允许对异常类型、消息和属性进行链式断言,无需依赖正则表达式或字符串匹配。

assertThrows() 如何获取异常实例
通过传入预期的异常类作为第一个参数,执行代码的 Executable 接口实现(通常是 Lambda 表达式)作为第二个参数,JUnit 5 会执行该代码块并在抛出异常时将其返回。如果代码未抛出异常,测试将失败;如果抛出了不同类型的异常,测试也会失败。获取到的异常对象可以直接赋值给变量,从而访问其所有公共方法和字段。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ExceptionTest {
@Test
public void testExceptionMessage() {
// 定义预期异常类和可执行代码
IllegalArgumentException thrown = assertThrows(
IllegalArgumentException.class,
() -> {
throw new IllegalArgumentException("User not found");
}
);
// 验证异常消息
assertEquals("User not found", thrown.getMessage());
}
}
上述代码中,assertThrows 成功捕获了 IllegalArgumentException,并将其赋值给 thrown 变量。随后通过 assertEquals 验证了消息字符串完全匹配。这种方式比旧版本的 @Rule ExpectedException 更直观,且类型安全。
如何处理嵌套异常或自定义异常属性
当需要验证异常的根原因或自定义字段时,可以在捕获异常后进一步检查其 getCause() 方法或特定属性。对于自定义异常,可以直接访问其定义的 getter 方法。这种处理方式适用于复杂业务逻辑中的多层异常传递场景,确保异常信息在传播过程中未被丢失或篡改。

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class NestedExceptionTest {
static class CustomException extends RuntimeException {
private final String errorCode;
public CustomException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() { return errorCode; }
}
@Test
public void testCustomExceptionAttributes() {
CustomException thrown = assertThrows(
CustomException.class,
() -> {
throw new CustomException("Database error", "DB_001");
}
);
// 验证标准消息
assertEquals("Database error", thrown.getMessage());
// 验证自定义属性
assertEquals("DB_001", thrown.getErrorCode());
}
}
在第二个示例中,CustomException 包含一个额外的 errorCode 字段。通过 assertThrows 捕获后,可以直接调用 getErrorCode() 来验证业务特定的错误码。这证明了 assertThrows 不仅限于标准消息验证,还能全面检查异常对象的内部状态。若需验证嵌套异常,可使用 thrown.getCause() 获取底层异常并继续断言,确保异常链的完整性。
当异常消息包含动态内容时如何验证
如果异常消息中包含动态生成的 ID 或时间戳,可以使用 contains() 或正则表达式进行部分匹配。虽然 assertThrows 本身不支持正则,但结合 String.matches() 或 Apache Commons Lang 的 StringUtils.containsIgnoreCase() 可以实现灵活验证。这种方法避免了因动态数据导致的测试不稳定问题。
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class DynamicMessageTest {
@Test
public void testDynamicMessageContainsId() {
int userId = 12345;
IllegalStateException thrown = assertThrows(
IllegalStateException.class,
() -> {
throw new IllegalStateException("User " + userId + " is locked");
}
);
// 验证消息包含特定ID
assertTrue(thrown.getMessage().contains(String.valueOf(userId)));
}
}
此示例展示了如何处理动态消息。通过 assertTrue 和 contains 方法,可以确保消息中包含关键标识符,而不必关心其他上下文文本。这种策略在集成测试中尤为有用,其中异常消息可能包含外部系统生成的唯一标识。

















