在单元测试期间,我在尝试测试和模拟类RestHighLevelClient
内部时遇到 NullPointerException ElasticClient
:
@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)