在JUnit 5中是否有更好的方法断言方法抛出异常?

目前,我必须使用@Rule来验证我的测试是否抛出异常,但这不适用于我希望多个方法在测试中抛出异常的情况。


当前回答

实际上,我认为这个特殊例子的文档中有一个错误。预期的方法是expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(

其他回答

您可以使用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"));
}

您可以使用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());
}

我的解决方案:

    protected <T extends Throwable> void assertExpectedException(ThrowingRunnable methodExpectedToFail, Class<T> expectedThrowableClass,
        String expectedMessage) {
    T exception = assertThrows(expectedThrowableClass, methodExpectedToFail);
    assertEquals(expectedMessage, exception.getMessage());
}

你可以这样称呼它:

    assertExpectedException(() -> {
        carService.findById(id);
    }, IllegalArgumentException.class, "invalid id");

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());

更简单的一行代码。使用Java 8和JUnit 5,本例不需要lambda表达式或花括号

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

@Test
void exceptionTesting() {

    assertThrows(MyException.class, myStackObject::doStackAction, "custom message if assertion fails..."); 

// note, no parenthesis on doStackAction ex ::pop NOT ::pop()
}