Published on

How to Assert an Exception and Message with JUnit5

Authors

When testing code you often want to test that a particular exception and message are thrown. The JUnit method to do this is Assertions.assertThrows. So to test a NullPointerException is thrown we would use this: Assertions.assertThrows(NullPointerException.class, ()-> {codeThatThrowsNPE;}) One thing not clear from the docs is how to test the exception message?

I came across this answer which clarifies this:

Throwable exceptionThatWasThrown = assertThrows(NullPointerException.class, () -> {
    codeThatThrows;
});

assertThat(exceptionThatWasThrown.getMessage(), equalTo("Message I expected to be thrown"));

And the same thing in Kotlin:

exceptionThatWasThrown: Throwable  = assertThrows(NullPointerException::class.java) {
    codeThatThrows
}

assertThat(exceptionThatWasThrown.message, equalTo("Message I expected to be thrown"))