JUnit 5: How to assert an exception is thrown?

2019-01-06 19:27发布

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.

8条回答
家丑人穷心不美
2楼-- · 2019-01-06 20:11

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.

Per the JUnit docs:

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

...

@Test
void exceptionTesting() {
    Executable closureContainingCodeToTest = () -> throw new IllegalArgumentException("a message");

    assertThrows(IllegalArgumentException.class, closureContainingCodeToTest, "a message");
}
查看更多
够拽才男人
3楼-- · 2019-01-06 20:13

Here is an easy way.

@Test
void exceptionTest() {

   try{
        model.someMethod("invalidInput");
        fail("Exception Expected!");
   }
   catch(SpecificException e){

        assertTrue(true);
   }
   catch(Exception e){
        fail("wrong exception thrown");
   }

}

It only succeeds when the Exception you expect is thrown.

查看更多
登录 后发表回答