vendredi 4 décembre 2015

Robolectric: run looper of handler in my case

I have a very simple class which has a Handler, when it handles message it sends new message again:

public class MyRepeatTask{
  …
  public void startTask() {
    // send message with delay 5 sec
    handler.sendMessageDelayed(handler.obtainMessage(…), 5000);
  }

  Handler  handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // I put a log for unit test
            System.out.println(“handling message …”);
            // send message with delay again
            handler.sendMessageDelayed(handler.obtainMessage(…), 5000);
        }
  }
}

As you see above, when startTask() is called, the handler starts sending a message in 5 seconds. Then, in handleMessage() callback, the handler again send a message with 5 seconds delay. The purpose of this is to repeatedly do some task(like System.out.println()).

I test the above class with Robolectric:

@RunWith(RobolectricTestRunner.class)
public class MyRepeatTaskTest {
  @Test
  public void testStartTask() {
    MyRepeatTask task = new MyRepeatTask();
    task.startTask();

    // run looper of ‘handler’ in task
    ShadowLooper shadowLooper = Shadows.shadowOf(task.handler.getLooper());
    shadowLooper.runToEndOfTasks();

    // sleep for 30 seconds
    Thread.sleep(30 * 1000);
  }
}

I expect to see the System.out.println() message “handling message …” every 5 seconds. However, when I run my test, I only see the message once in terminal.

It looks like the handler ’s Looper has only run for one task, then it stopped.

If I am right, how to keep the looper running all the time in Robolectric? If I am wrong, why I only see one log message?

Aucun commentaire:

Enregistrer un commentaire