In Robolectric test, how to wait for messages in the main looper to be run?

坚强是说给别人听的谎言 提交于 2019-12-11 20:33:05

问题


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?


回答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.



来源:https://stackoverflow.com/questions/31696100/in-robolectric-test-how-to-wait-for-messages-in-the-main-looper-to-be-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!