在JUnit 5中,有没有更好的方法来断言方法抛出了异常?
目前,我必须使用@Rule来验证我的测试是否抛出了异常,但这不适用于我期望在测试中有多个方法抛出异常的情况。
发布于 2016-10-27 01:19:17
您可以使用assertThrows()
,它允许您在同一个测试中测试多个异常。由于Java8对lambda的支持,这是在JUnit中测试异常的标准方法。
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"));
}
发布于 2017-04-03 00:27:32
他们在JUnit 5中对其进行了更改(期望的: InvalidArgumentException,实际的:调用的方法),代码如下:
@Test
public void wrongInput() {
Throwable exception = assertThrows(InvalidArgumentException.class,
()->{objectName.yourMethod("WRONG");} );
}
发布于 2017-05-16 16:28:05
您可以使用assertThrows()
。我的例子取自文档的http://junit.org/junit5/docs/current/user-guide/
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
....
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
https://stackoverflow.com/questions/40268446
复制相似问题