在单元测试期间,当尝试测试和模拟ElasticClient
类中的RestHighLevelClient
时,我面临NullPointerException:
@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)
问题源于RestHighLevelClient
中的ping
方法是final
,因为无法定期模拟。
因此,我使用了这个关于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();
}
您需要通过以下步骤为mock添加一个mockito扩展:
- 创建一个名为"的文件夹;mockito扩展";在测试资源中文件夹
- 添加一个名为";org.mockito.plugins.MockMaker"内部文件夹
- 在该文件中;mock maker inline">
尝试:
when(restHighLevelClient.ping(eq(RequestOptions.DEFAULT))).thenReturn(true);