You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何正确Mock NotFoundException 避免调用getError()时报空指针

根因分析
  • 你调用thenThrow时传入的NotFoundException实例的error字段为null,导致catch块执行ex.getError()时触发空指针。
  • anyString()、eq(any())均为错误用法:any*系列参数匹配器仅可在when()方法内做参数匹配使用,不能用于构造实际对象;eq()的入参需要是具体匹配值,不可以嵌套参数匹配器,不需要精确匹配参数时直接写any()即可。
解决方案

方案1:直接构造带有效Error属性的异常实例

直接使用三参数构造方法初始化NotFoundException,提前传入非空的Error对象:

// 构造非空Error实例,可根据业务需要初始化属性
Error error = new Error();
// 构造完整的NotFoundException对象
NotFoundException exception = new NotFoundException("testResource", "testId", error);
// 配置Mock方法抛出异常
when(service.filter(any(), any(), any()))
        .thenThrow(exception);

方案2:Mock异常对象的getError返回值

如果NotFoundException的error字段没有对外暴露的初始化入口,可以直接Mock异常实例,指定getError()的返回值:

// Mock异常实例
NotFoundException mockException = Mockito.mock(NotFoundException.class);
// Mock非空Error返回
Error mockError = new Error();
when(mockException.getError()).thenReturn(mockError);
// 配置Mock方法抛出异常
when(service.filter(any(), any(), any()))
        .thenThrow(mockException);

内容的提问来源于stack exchange,提问作者Another

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 09:18:02