在Robolectric测试,如何等待在主活套消息要运行? [英] In Robolectric test, how to wait for messages in the main looper to be run?

查看:262
本文介绍了在Robolectric测试,如何等待在主活套消息要运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试使用Robolectric 3.一旦运行一个服务,它会注册一个匿名BroadcastReceive等待系统发送一个广播发生了一些事件之后。

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.

在测试中,我初始化服务,以便它注册的BroadcastReceiver,那么我将触发系统事件,那么我验证服务状态相应改变广播处理后。但由于的onReceive 方法异步运行,则断言为时过早运行。

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.

但是,使用视频下载在测试中没有工作(和它的code气味我猜),的onReceive 无论如何都不会叫。

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

这样一步一步的调试到Robolectric code我看到的BroadcastReceiver正确注册和广播被发送到主尺蠖的调度程序,但后来什么也没有发生。

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?

推荐答案

在Robolectric,服务的调度通常处于暂停状态。不运行放入队列中的任何消息,直到时间不是由一定量的高级。

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.

给定一个服务为myService ,您可以访问其Robolectric调度和运行其入队的消息:

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

请注意,快捷键 Robolectric.flushForegroundThreadScheduler()只运行全部原来在当时的队列中的消息;如果把其中任何其他的消息,他们将不会被执行。

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.

这篇关于在Robolectric测试,如何等待在主活套消息要运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆