Junit 验证exception的几种方法

本文介绍了在JUnit测试中验证异常的几种方法,包括使用try-catch、JUnit4的ExpectedException Rule以及JUnit5的assertThrows。assertThrows不仅能让测试更易读,还允许对捕获的异常进行进一步断言,如检查异常消息。

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

  1. try - catch

    @Test
    public void testInvalidData() {
        prepareTestData();
    
        try {
            userService.fetchUser(1234);
            Assert.fail("IllegalArgumentException not thrown");
        } catch (IllegalArgumentException expected) {
        }
    }
  2. Annotation Attribute

    @Test(expected = IllegalArgumentException.class)
    public void testInvalidData() {
        prepareTestData();
    
        // should throw IllegalArgumentException
        userService.fetchUser(1234);
    }

    Junit5 以后不再有这个feature

  3. Rule ExpectedException

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void testInvalidData() {
        prepareTestData();
    
        thrown.expect(IllegalArgumentException.class);
        userService.fetchUser(1234);
    }

    JUnit 4 contains the built-in rule ExpectedException. (please remember that JUnit 5 uses extensions instead of rules).

    This approach is similar to try-catch and @Test(expected = ...), but we can control from which point the exception is expected.

  4. assertThrows

    @Test
    public void testInvalidData() {
        prepareTestData();
    
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            userService.fetchUser(1234);
        });
    }

    Assertions.assertThrows also returns the exception object to execute further asserts, e.g. to assert the message. 

 

Summary

I try to use assertThrows as often as possible because the test code gets both readable and flexible. But all the other mentioned approaches are also valid if correctly used.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值