使用Algolia Android客户端进行单元测试时死锁

时间:2017-03-01 22:24:43

标签: android unit-testing testing junit algolia

我正在尝试在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();

1 个答案:

答案 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");
    }