如何全局抑制Java/IntelliJ中ThrowableResultOfMethodCallIgnored警告?
解决断言工具方法的"Result of 'assertThrowsWithCause()' not thrown"警告问题
方案1:给工具方法添加注解并引入依赖
在你的assertThrowsWithCause方法上添加@SuppressWarnings("ThrowableResultOfMethodCallIgnored")注解,同时确保项目引入IntelliJ的注解库,让IDE识别该方法返回的Throwable无需处理:
首先添加Maven依赖(Gradle可对应调整):
<dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>24.0.1</version> <scope>test</scope> </dependency>
修改工具方法:
@SuppressWarnings("ThrowableResultOfMethodCallIgnored") public static <T, U extends Throwable> Throwable assertThrowsWithCause( Class<T> expectedOuterExceptionType, Class<U> expectedInnerExceptionType, Executable executable) { Exception outerException = assertThrows(Exception.class, executable); assertEquals(expectedOuterExceptionType, outerException.getClass()); assertEquals(expectedInnerExceptionType, outerException.getCause().getClass()); return outerException.getCause(); }
方案2:项目级全局配置抑制警告
通过IntelliJ的检查配置创建项目级规则,所有成员拉取代码后自动生效:
- 打开IntelliJ的
Settings→Editor→Inspections - 定位到
Java→Probable bugs→Throwable result of method call ignored - 点击右侧的配置按钮,选择
Copy to Project,生成项目专属的检查配置 - 在Scope中选择
Tests,然后禁用该检查,或者将你的工具方法添加到排除列表 - 配置文件会保存到项目的
.idea/inspectionProfiles目录,提交到版本仓库即可共享给所有成员
方案3:修改工具方法返回类型为void
如果测试代码不需要用到返回的异常实例,直接将方法返回类型改为void,IDE就不会触发未处理返回值的警告:
public static <T, U extends Throwable> void assertThrowsWithCause( Class<T> expectedOuterExceptionType, Class<U> expectedInnerExceptionType, Executable executable) { Exception outerException = assertThrows(Exception.class, executable); assertEquals(expectedOuterExceptionType, outerException.getClass()); assertEquals(expectedInnerExceptionType, outerException.getCause().getClass()); }
方案对比
- 方案1:精准控制,仅抑制该工具方法的警告,不影响其他代码的检查,推荐使用
- 方案2:全局生效,无需修改代码,但可能遗漏其他需要处理的Throwable场景
- 方案3:实现最简单,但无法满足需要使用返回异常实例的测试场景
内容的提问来源于stack exchange,提问作者Andrew Cheong
相关产品推荐
相关产品推荐

