JUnit4如何断言确定异常的抛出

本文介绍在JUnit4中如何测试特定异常是否被抛出。通过使用@Test注解的expected属性或ExpectedException规则,可以有效地验证方法调用是否引发了预期的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java 必知必会 第 35 篇

how do you assert that a certain exception is thrown in junit-4 tests

问题

在JUnit4单元测试中,我要怎样做才能测试出有特定的异常抛出?我能想到的就只有下面的方法:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    boolean thrown = false;

    try {
        foo.doStuff();
    } catch (IndexOutOfBoundsException e) {
        thrown = true;
    }

    assertTrue(thrown);
}
回答1

在JUnit4后支持下面的写法:

@Test(expected=IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
    ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);
}

(译者:在@Test注解内提供了expected属性,你可以用它来指定一个Throwble类型,如果方法调用中抛出了这个异常,那么这条测试用例就相当于通过了)

回答2

如果你使用的是JUnit4.7,你可以使用如下的期望异常规则来验证异常信息:

public class FooTest {
    @Rule
    public final ExpectedException exception = ExpectedException.none();

    @Test
    public void doStuffThrowsIndexOutOfBoundsException() {
        Foo foo = new Foo();

        exception.expect(IndexOutOfBoundsException.class);
        foo.doStuff();
    }
}

这种方式比@Test(expected=IndexOutOfBoundsException.class)要更好,如果是在调用foo.doStuff()方法之前就已经抛出异常的话,测试结果就不是我们想要的了。
(译者:同时,ExpectedException还能够验证异常信息,如exception.expectMessage("there is an exception!");

拓展阅读
  1. JUnit:使用ExpectedException进行异常测试
  2. JUnit4 用法详解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这就是编程

让我看到你的头像

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值