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:
assertThrows(Class<T> expectedType, Executable executable)
assertThrows(Class<T> expectedType, Executable executable, String message)
assertThrows(Class<T> expectedType, Executable executable, Supplier<String> messageSupplier)
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?