You need to enable JavaScript to run this app. 使用Mockito模拟RestHighLevelClient时出现NPE的问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用Mockito模拟RestHighLevelClient时出现NPE的问题求助

问题根因定位
  • 空指针触发逻辑:默认配置下的Mockito使用子类代理模式生成mock对象,而RestHighLevelClient没有公开的无参构造方法,类内部的index()方法实现没有做可代理隔离,导致生成的mock对象没有真正拦截方法调用,直接走到了真实类的执行分支。此时类内部依赖的底层RestClient实例未初始化,为null,调用performRequest时直接抛出空指针。
  • 现有代码存在的其他问题:
    • 业务代码构造方法名和类名不匹配:类名是CreateIndex,但构造方法写为IndexService,会直接编译失败
    • 打桩时手动new的IndexRequest对象没有重写equals/hashCode,即使mock生效,也会因为对象内存地址不匹配导致参数校验失败,打桩逻辑不生效
    • 打桩用到的indexResponse变量未初始化,哪怕不抛空指针,也会返回null值
正确解决流程

1. 开启Mockito inline mock模式

在测试资源目录下创建配置文件,替换传统的子类代理模式:

  • 文件路径:src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
  • 文件内容:mock-maker-inline
    该配置让Mockito通过字节码修改的方式直接拦截方法调用,不需要依赖无参构造就能正确mockRestHighLevelClient这类无公共无参构造的具体类,也能正常拦截类中的final方法。

注:如果使用JUnit5 + 3.4以上版本的Mockito,默认已开启inline模式,不需要手动创建上述配置文件。

2. 替换打桩参数为匹配器

IndexRequest没有重写equals方法,不能直接传入实例做参数匹配,所有入参要替换为Mockito提供的匹配器。注意:一旦使用参数匹配器,方法的所有入参都必须使用匹配器,不能混合真实对象和匹配器。

3. 补全测试逻辑

完整可运行的测试代码参考如下:

public class TestCreateIndex {
    // 预设的mock返回值
    private IndexResponse presetResponse;
    private CreateIndex createIndex;

    @Mock
    private RestHighLevelClient elasticClient;

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Before
    public void setUp() throws IOException {
        // 初始化预设的IndexResponse(根据实际业务需要构造即可)
        presetResponse = new IndexResponse(
            new ShardId("test-index", "_doc", 1),
            "id", 1, 0, 1, true
        );
        // 初始化待测试类
        createIndex = new CreateIndex(elasticClient);
    }

    @Test
    public void createIndex_whenElasticSuccess_shouldReturnTrue() throws IOException {
        // 打桩:匹配任意IndexRequest、默认请求选项时,返回预设成功响应
        Mockito.when(elasticClient.index(
            Mockito.any(IndexRequest.class),
            Mockito.eq(RequestOptions.DEFAULT)
        )).thenReturn(presetResponse);

        // 调用业务方法
        boolean result = createIndex.createIndex("1", "test-index");

        // 断言业务返回值正确
        Assertions.assertTrue(result);
        // 验证客户端方法确实被调用1次
        Mockito.verify(elasticClient, Mockito.times(1)).index(
            Mockito.any(IndexRequest.class),
            Mockito.eq(RequestOptions.DEFAULT)
        );

        // 捕获实际传入的请求对象,校验参数和业务预期一致
        ArgumentCaptor<IndexRequest> requestCaptor = ArgumentCaptor.forClass(IndexRequest.class);
        Mockito.verify(elasticClient).index(requestCaptor.capture(), Mockito.eq(RequestOptions.DEFAULT));
        IndexRequest actualRequest = requestCaptor.getValue();
        Assertions.assertEquals("1", actualRequest.id());
        Assertions.assertEquals("test-index", actualRequest.index());
    }

    @Test
    public void createIndex_whenElasticThrowIOException_shouldReturnFalse() throws IOException {
        // 打桩:调用客户端方法时抛出IO异常
        Mockito.when(elasticClient.index(
            Mockito.any(IndexRequest.class),
            Mockito.eq(RequestOptions.DEFAULT)
        )).thenThrow(new IOException("connect failed"));

        boolean result = createIndex.createIndex("1", "test-index");

        // 断言异常场景下业务返回false
        Assertions.assertFalse(result);
    }
}
避坑提示
  • 不要为了mockRestHighLevelClient去手动构造底层RestClient的mock实例,这种方式需要额外处理请求序列化、响应解析逻辑,测试代码维护成本极高,完全没必要。
  • 打桩时不要硬编码具体的请求对象做匹配,优先使用any()类匹配器,需要严格校验参数时用ArgumentCaptor捕获实际传入的对象做校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 16:15:04