有没有更好的方法来断言方法会在JUnit 5中引发异常?

当前,我必须使用@Rule来验证我的测试引发了异常,但这不适用于我希望多种方法在测试中引发异常的情况。

最佳答案

您可以使用 assertThrows() ,它允许您在同一测试中测试多个异常。有了Java 8中对lambda的支持,这是在JUnit中测试异常的规范方法。
根据JUnit docs:

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

@Test
void exceptionTesting() {
    MyException thrown = assertThrows(
           MyException.class,
           () -> myObject.doThing(),
           "Expected doThing() to throw, but it didn't"
    );

    assertTrue(thrown.getMessage().contains("Stuff"));
}

10-06 10:02
查看更多