JUnit 5: How to assert an exception is thrown? JUnit 5: How to assert an exception is thrown? java java

JUnit 5: How to assert an exception is thrown?


You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

Per the JUnit docs:

import static org.junit.jupiter.api.Assertions.assertThrows;@Testvoid exceptionTesting() {    MyException thrown = assertThrows(           MyException.class,           () -> myObject.doThing(),           "Expected doThing() to throw, but it didn't"    );    assertTrue(thrown.getMessage().contains("Stuff"));}


In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows.Using org.junit.jupiter.api.Assertions.assertThrows

public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

If no exception is thrown, or if an exception of a different type is thrown, this method will fail.

If you do not want to perform additional checks on the exception instance, simply ignore the return value.

@Testpublic void itShouldThrowNullPointerExceptionWhenBlahBlah() {    assertThrows(NullPointerException.class,            ()->{            //do whatever you want to do here            //ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null);            });}

That approach will use the Functional Interface Executable in org.junit.jupiter.api.

Refer :


They've changed it in JUnit 5 (expected: InvalidArgumentException, actual: invoked method) and code looks like this one:

@Testpublic void wrongInput() {    Throwable exception = assertThrows(InvalidArgumentException.class,            ()->{objectName.yourMethod("WRONG");} );}