在 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"));
}
关于java - JUnit 5 : How to assert an exception is thrown?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40268446/