java - 如何使用 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
三种方法检查是否抛出异常:
assertThrows(Class<T> expectedType, Executable executable)
assertThrows(Class<T> expectedType, Executable executable, String message)
assertThrows(Class<T> expectedType, Executable executable, Supplier<String> messageSupplier)
它们都没有提供检查字符串是否以另一个字符串开头的机制。最后两个方法只检查字符串是否相等。我如何轻松检查异常消息是否以开头,"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"));
可悲的是,它不存在。任何解决方法?
解决方案
该assertThrows()
方法返回预期类型的异常实例(如果有)。然后,您可以手动从 is 获取消息并检查它是否以您想要的字符串开头。
这是来自文档的示例
@Test
void exceptionTesting() {
Exception exception = assertThrows(ArithmeticException.class, () ->
calculator.divide(1, 0));
assertEquals("/ by zero", exception.getMessage());
}
推荐阅读
- angular - Angular - 带有预构建插件的 Monorepo
- flutter - 我如何在颤动中创建这个自定义交错网格?
- javascript - Firestore - 保存数组
- javascript - Nodejs异步函数在执行前打印数据钓鱼
- java - 为什么字符串无法以默认字符集编码?
- c# - 为什么我会为 Children.Add 上的现有密钥获得 ArgumentException?
- javascript - react-native FlatList 的 RenderFeed 函数 - 错误:对象作为 React 子项无效
- css-grid - css 网格中的最大列数和/或行数是多少
- xamarin - Shell.Current.GoToAsync 不适用于 UWP
- sql - 将 EXEC master..xp_cmdshell 'Query User' 的结果插入表列中