0

I'm testing a Service using Robolectric 3. Once run, it registers an anonymous BroadcastReceive waits for the system to send a broadcast after some event occurred.

In the test I initialize the service so that it registers the BroadcastReceiver, then I trigger the system event, then I verify that the service state changed accordingly after the broadcast is handled. But because the onReceive method is run asynchronously, the assertions are run too soon.

But using Thread.sleep in the test didn't work (and it's code smell I guess), onReceive is not called anyway.

Doing step-by-step debugging into Robolectric code I see the BroadcastReceiver is correctly registered and the broadcast is sent to the main looper's scheduler, but then nothing happens.

So how can I make the main scheduler run the pending actions and let my test wait for their completion?

ris8_allo_zen0
  • 1,537
  • 1
  • 15
  • 35

1 Answers1

0

In Robolectric, the scheduler of a Service is normally in paused state. Any message that is put into the queue is not run until the time is not "advanced" by certain amount.

Given a Service myService, you can access its Robolectric scheduler and run its enqueued messages:

org.robolectric.util.Scheduler scheduler = shadowOf(myService.get().getMainLooper()).getScheduler();
while (!scheduler.advanceToLastPostedRunnable()) ;

// ... put your test assertions here

Please note that the shortcut Robolectric.flushForegroundThreadScheduler() only runs all the messages that were in the queue at that time; if any of those put other messages, they won't be executed.

ris8_allo_zen0
  • 1,537
  • 1
  • 15
  • 35