当使用Elasticsearch async api的
HighLevelRestClient
v7.5时,我该如何控制IndexResponse
?也许我需要模拟Low Level REST Client并将其用于我的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;
}
}
更新 示例项目 使用Oleg的答案
RestHighLevelClient
是在doIt
中创建的,那么你无法进行单元测试。 - Oleg