JUnit 5预期异常

在JUnit 5中,我们可以使用assertThrows声明抛出了异常。

PS已通过JUnit 5.5.2测试

1.未检查的异常

1.1捕获运行时异常的JUnit示例。

ExceptionExample1.java
package com.mkyong.assertions;

import org.junit.jupiter.api.Test;

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

public class ExceptionExample1 {

    @Test
    void test_exception() {

        Exception exception = assertThrows(
			ArithmeticException.class, 
			() -> divide(1, 0));

        assertEquals("/ by zero", exception.getMessage());

        assertTrue(exception.getMessage().contains("zero"));

    }

    int divide(int input, int divide) {
        return input / divide;
    }
}

2.检查异常

2.1捕获自定义/编译时间异常的JUnit示例。

NameNotFoundException.java
package com.mkyong.assertions;

public class NameNotFoundException extends Exception {
    public NameNotFoundException(String message) {
        super(message);
    }
}
ExceptionExample2.java
package com.mkyong.assertions;

import org.junit.jupiter.api.Test;

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

public class ExceptionExample2 {

    @Test
    void test_exception_custom() {
        Exception exception = assertThrows(
			NameNotFoundException.class, 
			() -> findByName("mkyong"));
			
        assertTrue(exception.getMessage().contains("not found"));
    }

    String findByName(String name) throws NameNotFoundException{
        throw new NameNotFoundException( name + " not found!");
    }
}

下载源代码

$ git clone https://github.com/mkyong/junit-examples
$ cd junit5-examples
$检查src / test / java / com / mkyong / assertions / *。java

参考文献

翻译自: https://mkyong.com/junit5/junit-5-expected-exception/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值