gpt4 book ai didi

java - 尝试模拟 Elastic Search 的 RestHighLevelClient 时出现 NullPointerException 问题

转载 作者:行者123 更新时间:2023-11-30 12:02:06 28 4
gpt4 key购买 nike

我在单元测试期间遇到 NullPointerException,当我尝试在 ElasticClient 类中测试和模拟 RestHighLevelClient 时:

@Configuration
@NoArgsConstructor
public class ElasticClient{

@Setter
private RestHighLevelClient restHighLevelClient;

@PostConstruct
public void buildRestHighLevelClient(){

RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(
"127.0.0.1",
9200, "http")
);

restClientBuilder.setRequestConfigCallback(
requestConfigBuilder ->
requestConfigBuilder
.setConnectTimeout(500000)
.setSocketTimeout(600000)
.setConnectionRequestTimeout(0)
)
.setHttpClientConfigCallback(
httpClientBuilder ->
httpClientBuilder
.setMaxConnPerRoute(2048)
);

restHighLevelClient = new RestHighLevelClient(restClientBuilder);
}

public boolean isReachable(){
return restHighLevelClient.ping(RequestOptions.DEFAULT);
}

}

和测试类:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class ElasticClientTest{

@Mock
private RestHighLevelClient restHighLevelClient;


ElasticClient elasticClient;

@Before
public void init(){

elasticClient = new ElasticClient();
elasticClient.setRestHighLevelClient(restHighLevelClient);

}

NullPointerException 来自这里:

    @Test
public void whenElasticIsPingable_thenReturnTrue() throws IOException{

when(restHighLevelClient.ping(RequestOptions.DEFAULT)).thenReturn(true);
Assertions.assertThat(elasticClient.isReachable()).isTrue();
}

这是堆栈跟踪:

java.lang.NullPointerException
at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1764)
at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1734)
at org.elasticsearch.client.RestHighLevelClient.ping(RestHighLevelClient.java:694)
at com.example.ElasticClientTest.whenElasticIsPingable_thenReturnTrue(ElasticClientTest.java:44)

最佳答案

问题源于 ping RestHighLevelClient 中的方法是final因为不能经常被 mock 。

所以,我使用了this example的帮助关于 PowerMock

最终结果:

@RunWith(PowerMockRunner.class)
@PrepareForTest(RestHighLevelClient.class)
public class ElasticClientTest{

ElasticClient elasticClient;

RestHighLevelClient restHighLevelClient;

@Before
public void init(){

restHighLevelClient = mock(RestHighLevelClient.class);

elasticClient = new ElasticClient();
elasticClient.setRestHighLevelClient(restHighLevelClient);

}


@Test
public void whenElasticIsPingable_thenReturnTrue() throws IOException{

when(restHighLevelClient.ping(RequestOptions.DEFAULT)).thenReturn(true);

Assertions.assertThat(elasticClient.isReachable()).isTrue();
}

关于java - 尝试模拟 Elastic Search 的 RestHighLevelClient 时出现 NullPointerException 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914298/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com