使用Mockito测试RestHighLevelClient别名更新时遇client.indices()为空的解决方法
解决client.indices()为null的Mockito测试问题
问题原因
你只对RestHighLevelClient做了mock,但没有对它的indices()方法进行打桩,导致调用该方法时返回null,进而触发空指针异常。另外原测试里直接mockIndicesAliasesRequest对象作为参数匹配,实际运行时传入的请求对象和这个mock对象不相等,也会导致打桩不生效。
解决方案
需要依次mockRestHighLevelClient和它返回的IndicesClient,并正确设置方法调用的返回值,同时用参数匹配器匹配请求对象:
import org.elasticsearch.client.IndicesClient; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @Test void testCreateAlias() throws IOException { // 1. 模拟IndicesClient实例 IndicesClient mockIndicesClient = mock(IndicesClient.class); // 2. 模拟RestHighLevelClient,让它的indices()返回模拟的IndicesClient RestHighLevelClient mockClient = mock(RestHighLevelClient.class); when(mockClient.indices()).thenReturn(mockIndicesClient); // 3. 给IndicesClient的updateAliases方法打桩,匹配任意请求对象 AcknowledgedResponse response = AcknowledgedResponse.of(true); when(mockIndicesClient.updateAliases(any(IndicesAliasesRequest.class), any(RequestOptions.class))) .thenReturn(response); // 4. 将模拟的client注入到searchManagerService中(根据实际情况选择构造器/setter/直接赋值) searchManagerService.client = mockClient; // 执行测试方法 searchManagerService.createAlias("test", "test_idx", true); }
关键说明
- 必须mock
IndicesClient并让client.indices()返回它,因为RestHighLevelClient的indices()方法默认返回null,不会自动mock内部依赖对象。 - 使用
any(IndicesAliasesRequest.class)替代直接mock请求对象,这样不管实际传入的请求是什么实例,打桩都会生效。 - 确保
searchManagerService中的client字段被替换为我们模拟的对象,具体注入方式根据你的服务类结构调整(比如构造器注入、setter方法)。
内容的提问来源于stack exchange,提问作者Rajesh Basnet
相关产品推荐
相关产品推荐

