在JUnit 5中是否有更好的方法断言方法抛出异常?
目前,我必须使用@Rule来验证我的测试是否抛出异常,但这不适用于我希望多个方法在测试中抛出异常的情况。
在JUnit 5中是否有更好的方法断言方法抛出异常?
目前,我必须使用@Rule来验证我的测试是否抛出异常,但这不适用于我希望多个方法在测试中抛出异常的情况。
当前回答
您可以使用assertThrows(),它允许您在同一个测试中测试多个异常。由于Java 8支持lambdas,这是JUnit中测试异常的规范方法。
根据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().contentEquals("Stuff"));
}
其他回答
这里有一个简单的方法。
@Test
void exceptionTest() {
try{
model.someMethod("invalidInput");
fail("Exception Expected!");
}
catch(SpecificException e){
assertTrue(true);
}
catch(Exception e){
fail("wrong exception thrown");
}
}
它只有在抛出您期望的异常时才会成功。
他们在JUnit 5中改变了它(预期:InvalidArgumentException,实际:invoked method),代码看起来像这样:
@Test
public void wrongInput() {
Throwable exception = assertThrows(InvalidArgumentException.class,
()->{objectName.yourMethod("WRONG");} );
}
我认为这是一个更简单的例子
List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());
在包含空数组列表的可选对象上调用get()将抛出NoSuchElementException异常。assertThrows声明预期的异常并提供lambda提供者(不接受参数并返回值)。
感谢@prime的回答,我希望能详细说明。
TL;DR:如果您使用的是JUnit 5.8.0+版本,您可以使用assertThrowsExactly()而不是assertThrows()来匹配确切的异常类型。
assertThrowsExactly(FileNotFoundException.class, () -> service.blah());
您可以使用assertThrows(),但是使用assertThrows,即使抛出的异常是子类型,您的断言也将通过。
这是因为,JUnit 5通过调用Class.isInstance(..)来检查异常类型,即使抛出的异常是子类型,Class.isInstance(..)也会返回true。
解决方法是在Class上断言:
Throwable throwable = assertThrows(Throwable.class, () -> {
service.readFile("sampleFile.txt");
});
assertEquals(FileNotFoundException.class, throwable.getClass());
This is what I do when testing to make sure an exception has been thrown
//when
final var tripConsumer = new BusTripConsumer(inputStream);
final Executable executable = () -> tripConsumer.deserialiseTripData();
//then
assertThrows(IllegalArgumentException.class, executable);