我正在尝试在JUnit测试中使用来自algolia的searchAsync
,但由于搜索结果没有回来,它会以死锁结束。这是我的代码:
final Index index = AlgoClient.initIndex("contacts");
Query query = new Query();
query.setHitsPerPage(100);
CountDownLatch signal = new CountDownLatch(1);
index.searchAsync(query, new CompletionHandler() {
@Override
public void requestCompleted(JSONObject content, AlgoliaException e) {
signal.countDown();
});
signal.await();
答案 0 :(得分:3)
您需要使用await超时,如果超时则失败。此外,您应该在CompletionHandler
:
final Index index = client.getIndex("contacts");
Query query = new Query().setHitsPerPage(100);
final CountDownLatch signal = new CountDownLatch(1);
index.searchAsync(query, new CompletionHandler() {
@Override
public void requestCompleted(JSONObject content, AlgoliaException e) {
if (e == null) {
signal.countDown(); // Request success
} else {
fail(e.getMessage()); // Request error
}
}
});
try {
if (!signal.await(10, TimeUnit.SECONDS)) { // returns false when timeout
fail("Didn't count down");
}
} catch (InterruptedException e) {
fail("interrupted");
}