本文对在 Junit 测试中如何对异常进行断言的几种方法进行说明。
使用 Junit 5
如果你使用 Junit 5 的话,你可以直接使用 assertThrows 方法来对异常进行断言。

代码如下:
Exception exception = assertThrows(NumberFormatException.class, () -> {
new Integer("one");
});
System.out.println(exception);
使用 AssertJ
使用 AssertJ ,你可以有不少方法进行选择。
我们尝试使用 assertThatThrownBy 和 assertThatExceptionOfType 2 个方法。
这 2 个方法的写法有点不一样,但是整体效果是差不多的。
考察如下代码:
// AssertJ assertThatThrownBy
assertThatThrownBy(() -> {
new Integer("one");
}).isInstanceOf(NumberFormatException.class).hasMessageStartingWith("For input string");
// AssertJ assertThatExceptionOfType
assertT











![【Osek网络管理测试】[TG3_TC3]tSleepRequestMin_L](https://img-blog.csdnimg.cn/direct/4d47d5f4c86847b8a30963dc3025c0be.png)



![【Osek网络管理测试】[TG3_TC5]等待总线睡眠状态_1](https://img-blog.csdnimg.cn/direct/d34de03cba2144f8b3676dfc80a5bcdf.png)



