In Robolectric Test, How To Wait For Messages In The Main Looper To Be Run?
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 in
Solution 1:
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.
Post a Comment for "In Robolectric Test, How To Wait For Messages In The Main Looper To Be Run?"