I have a very simple class that Handler has, when it processes a message, it sends a new message again:
public class MyRepeatTask{ β¦ public void startTask() {
As you see above, when startTask() is called, the handler starts sending a message after 5 seconds. Then, in the handleMessage() callback, the Handler will again send a message with a delay of 5 seconds. The purpose of this is to repeatedly perform some task (for example, System.out.println() ).
I am testing the above Robolectric class:
@RunWith(RobolectricTestRunner.class) public class MyRepeatTaskTest { @Test public void testStartTask() { MyRepeatTask task = new MyRepeatTask(); task.startTask();
I expect to see the System.out.println() handling message β¦ " handling message β¦ " every 5 seconds. However, when I run my test, I only see the message once in the terminal.
It seems that Handler s Looper only works for one task, and then it stopped.
If I'm right, how to keep the looper all the time in Robolectric? If I am wrong, why do I see only one log message?
=========== UPDATE ============
I tried @rds answer, I replaced Thread.sleep(30 * 1000); on:
for (int i = 0; i < N; i++){ shadowLooper.runToEndOfTasks(); }
Now I see N times " handling message β¦ ". BUT, the entire test does not simulate a delay. I have a 5 second delay when sending a message using handler.sendMessageDelayed(handler.obtainMessage(β¦), 5000) , so the Robolectric framework does not mimic this delay message at all? How can I delay in my test?
java android unit-testing robolectric
user842225
source share