Robolectric不执行Runnable

时间:2016-07-04 10:38:34

标签: android unit-testing robolectric android-handler

Robolectric(3.1)应该能够执行发布到处理程序的runnable。

@Test
public void shouldExecuteRunnable() throws Exception {
    final CountDownLatch signal = new CountDownLatch(1);
    final boolean[] result = {false};
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            result[0] = true;
            signal.countDown();
        }
    };

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    handler.post(runnable);

    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();

    signal.await(5, TimeUnit.SECONDS);

    Assert.assertTrue(result[0]);
}

断言时测试失败。我错过了什么吗?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

@Test
public void shouldExecuteRunnable() throws Exception {
    final boolean[] result = {false};

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            result[0] = true;
        }
    };

    ShadowLooper.pauseMainLooper();

    Handler handler = new Handler();
    handler.post(runnable);

    ShadowLooper.runMainLooperOneTask();

    Assert.assertTrue(result[0]);
}

答案 1 :(得分:0)

有同样的问题, 这修好了它:

        ShadowLooper threadShadow = shadowOf(thread.getLooper());
        threadShadow.runOneTask();