前置:
外部方法无法捕获内部方法中已经被catch的异常(屏蔽catch后又throw异常的场景)junit测试框架场景2是本文重点
场景1:如果方法中throw一个异常,没有catch:
public static Integer convertToInt(String str) {if (str == null || str.trim().length() == 0) { throw new IllegalArgumentException("String must be not null or empty"); } return Integer.valueOf(str);}
针对这类型场景,可以使用如下方法进行异常的断言:
(1) 断言类型+断言消息:assertThrows+assertEquals
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {convertToInt(st);});assertEquals("String must be not null or empty", exception.getMessage());
(2)通过try....catch方法:try代码块中添加fail方法
try{convertToInt(st);fail("Param null")}catch(Exception e){};...//断言代码块
场景2:如果方法中throw一个异常,但是已经catch:
public static void exceptionWhenNull(String str) {if