使用 Elasticsearch 时如何控制 IndexResponse
async api带有 HighLevelRestClient
v7.5?
也许我需要模拟 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;
}
}
更新 Sample project使用 Oleg 的回答
最佳答案
模拟 RestHighLevelClient
然后在 indexAsync
模拟 IndexResponse
并将其传递给 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);
此外,配置 Mockito 以支持模拟 final 方法,否则 NPE将在模拟 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
关于java - 如何使用 Elasticsearch async api 控制响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403460/