Is there a better way to assert that a method throws an exception in JUnit 5?
Currently, I have to use an @Rule in order to verify that my test throws an exception, but this doesn't work for the cases where I expect multiple methods to throw exceptions in my test.
解决方案
You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is probably going to become the canonical way to test for exceptions in JUnit.
import static org.junit.jupiter.api.Assertions.assertThrows;
...
@Test
void exceptionTesting() {
Executable closureContainingCodeToTest = () -> throw new IllegalArgumentException("a message");
assertThrows(IllegalArgumentException.class, closureContainingCodeToTest, "a message");
}