How to control the response with the Elasticsearch async api
Mock RestHighLevelClient
then inside indexAsync
mock IndexResponse
and pass it to the ActionListener
.
RestHighLevelClient restHighLevelClient = mock(RestHighLevelClient.class);when(restHighLevelClient.indexAsync(any(), any(), any())).then(a -> { ActionListener<IndexResponse> listener = a.getArgument(2); IndexResponse response = mock(IndexResponse.class); when(response.getResult()).then(b -> { return Result.UPDATED; }); listener.onResponse(response); return null;});MyHelper myHelper = new MyHelper(restHighLevelClient);Boolean result = myHelper.doIt(null).get();assertFalse(result);
Also, configure Mockito to support mocking final methods otherwise a NPE will be thrown when mocking indexAsync
.
Instead of using the mockito-core artifact, include the mockito-inline artifact in your project
Create a file
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
withmock-maker-inline
as the content