首页 > 解决方案 > 如何使用 jUnit 5 Assertions 检查异常消息是否以字符串开头?

问题描述

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

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

dateTime简而言之,抛出的异常在其消息中具有可变部分:

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

从版本开始,我使用5.4.0提供Assertions三种方法检查是否抛出异常:

它们都没有提供检查字符串是否以另一个字符串开头的机制。最后两个方法只检查字符串是否相等。我如何轻松检查异常消息是否以开头,"Either request is too old"因为同一消息中可能会出现更多消息变化InvalidParameterException


我很欣赏一种方法,如果谓词返回assertThrows​(Class<T> expectedType, Executable executable, Predicate<String> messagePredicate),谓词将提供抛出并且断言通过,例如:messagetrue

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

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

标签: javaexceptionjunitjunit5assertion

解决方案


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

这是来自文档的示例

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

推荐阅读