mrtowel mrtowel - 3 months ago 56
Android Question

Robolectric does not execute Runnable

Robolectric (3.1) should be able to execute runnable posted to the handler.

@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]);
}


Test fails on assertion. Am I missing something?

Any help will be appreciated.

Answer
@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]);
}