How can I control the IndexResponse
when using the Elasticsearch async api w/ the HighLevelRestClient
v7.5?
Maybe I need to mock the Low Level REST Client and use that mock for my High Level REST Client? 🤔
@Test
void whenIndexResponseHasFailuresDoItShouldReturnFalse() {
// arrange
var indexResponse = mock(IndexResponse.class);
when(indexResponse.getResult()).thenReturn(Result.UPDATED);
var restHighLevelClient = mock(RestHighLevelClient.class);
when(restHighLevelClient.indexAsync())
//do something here??
var indexReqest = new IndexRequest(...);
//act
var myHelper = new MyHelper(restHighLevelClient);
var result = myHelper.doIt(indexReqest)
.get();
//assert
assert(result).isFalse();
}
class MyHelper {
//injected RestHighLevelClient
CompletableFuture<Boolean> doIt(Customer customer) {
var result = new CompletableFuture<Boolean>();
var indexRequest = new IndexRequest(...);
restHighLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT
, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) { //want to control indexResponse
if (indexResponse.getResult() == Result.UPDATED) {
result.complete(false);
} else {
result.complete(true);
}
}
@Override
public void onFailure(Exception e) {
...
}
});
return result;
}
}
Update Sample project using Oleg's answer
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
.
Option 1
Instead of using the mockito-core artifact, include the mockito-inline artifact in your project
Option 2
Create a file
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
withmock-maker-inline
as the content
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With