javaexceptionjunitjunit5assertion

How to use jUnit 5 Assertions to check, whether exception message starts with a String?


I use org.junit.jupiter.api.Assertions object to assert an exception is thrown:

Assertions.assertThrows(
        InvalidParameterException.class,
        () -> new ThrowingExceptionClass().doSomethingDangerous());

Simplified, the exception thrown has a variable part dateTime in its message:

final String message = String.format("Either request is too old [dateTime=%s]", date);
new InvalidParameterException(message);

As of version I use 5.4.0 the Assertions provide three methods checking the exception is thrown:

Neither of them provides a mechanism checking whether a String starts with another String. The last 2 methods only check whether the String is equal. How do I check easily whether the exception message starts with "Either request is too old" since more message variations might occur within the same InvalidParameterException?


I'd appreciate a method assertThrows​(Class<T> expectedType, Executable executable, Predicate<String> messagePredicate) where the predicate would provide the thrown message and the assertion passes when if predicate returns true such as:

Assertions.assertThrows(
    InvalidParameterException.class,
    () -> new ThrowingExceptionClass().doSomethingDangerous()
    message -> message.startsWith("Either request is too old"));

Sadly, it doesn't exist. Any workaround?


Solution

  • The assertThrows() method returns an exception instance of the expected type (if any). You can then manually get a message from it and check if it starts with the string you desire.

    Here is a sample from doc

    @Test
    void exceptionTesting() {
        Exception exception = assertThrows(ArithmeticException.class, () ->
            calculator.divide(1, 0));
        assertEquals("/ by zero", exception.getMessage());
    }