如何使用 jUnit 5 断言检查异常消息是否以字符串开头?

Nik*_*las 5 java junit exception assertion junit5

我使用org.junit.jupiter.api.Assertions对象来断言抛出异常:

Assertions.assertThrows(
        InvalidParameterException.class,
        () -> new ThrowingExceptionClass().doSomethingDangerous());
Run Code Online (Sandbox Code Playgroud)

简单地说,抛出的异常dateTime在其消息中有一个可变部分:

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

随着版本我用5.4.0Assertions提供三种方法检查异常被抛出:

它们都没有提供检查字符串是否另一个字符串开头的机制。最后 2 个方法只检查 String 是否相等。我如何轻松检查异常消息是否以 开头,"Either request is too old"因为在同一InvalidParameterException.


我很欣赏一种方法assertThrows?(Class<T> expectedType, Executable executable, Predicate<String> messagePredicate),其中谓词将提供抛出message的断言,并且当谓词返回时断言通过,true例如:

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

可悲的是,它不存在。任何解决方法?

lot*_*tor 11

assertThrows返回预期类型的​​异常实例(如果有)。然后,您可以手动从 is 获取消息并检查它是否以您想要的字符串开头。

这是来自文档的示例

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