You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JUnit的@Test注解方法中验证方法是否抛出异常?

在JUnit中测试方法抛出异常的几种方式

下面针对你的需求,提供三种常用的实现方式:

1. JUnit 4 快捷方式:使用@Test注解的expected属性

直接在@Test注解中指定期望捕获的异常类型,代码简洁直观:

@Test(expected = IllegalArgumentException.class)
public void testGenerateInvalidStudentData() {
    studentIdGenerator.generate(null, 2);
}

当generate方法抛出IllegalArgumentException时测试通过,若未抛出或抛出其他异常则测试失败。

2. JUnit 5(Jupiter)推荐方式:使用assertThrows

JUnit 5提供了更灵活的assertThrows方法,不仅能验证异常类型,还能获取异常对象做额外断言:

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
public void testGenerateInvalidStudentData() {
    // 捕获并验证异常类型
    IllegalArgumentException thrownException = assertThrows(
        IllegalArgumentException.class,
        () -> studentIdGenerator.generate(null, 2)
    );

    // 可选:验证异常的具体消息
    // assertEquals("studentId参数不能为null", thrownException.getMessage());
}

3. 通用兼容方式:手动try-catch捕获

这种方式适用于所有JUnit版本,适合需要复杂逻辑判断的场景:

import static org.junit.Assert.fail; // JUnit 4
// 或 import static org.junit.jupiter.api.Assertions.fail; // JUnit 5

@Test
public void testGenerateInvalidStudentData() {
    try {
        studentIdGenerator.generate(null, 2);
        // 如果代码执行到这里,说明未抛出预期异常,标记测试失败
        fail("预期抛出IllegalArgumentException,但未捕获到该异常");
    } catch (IllegalArgumentException e) {
        // 捕获到期望的异常,测试通过
    }
}

内容的提问来源于stack exchange,提问作者ahmad bagheri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:02:07