本文对在 Junit 测试中如何对异常进行断言的几种方法进行说明。

使用 Junit 5

如果你使用 Junit 5 的话,你可以直接使用 assertThrows 方法来对异常进行断言。

Junit 测试中如何对异常进行断言_java

代码如下:

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
        assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> {
            new Integer("one");
        });

上面代码中,对有关断言的使用进行了一些说明。