【问题标题】:Why is there no test instrumentation for BroadcastReceiver?为什么没有广播接收器的测试工具?
【发布时间】:2010-11-01 23:34:19
【问题描述】:
也许我错过了什么。我想为 BroadcastReceiver 编写测试用例;具体来说,它用于接收 BOOT_COMPLETED 事件并设置警报以供另一个接收器稍后处理;它似乎没有正确设置它,但关键是我没有明显的方法来测试它。我无法完全附加调试器并等待 BOOT_COMPLETED,也无法发送虚假的 BOOT_COMPLETED 广播。
为什么有 Activity、Service 和 Provider 的检测类,但没有 BroadcastReceiver?对此有什么建议吗?
【问题讨论】:
标签:
android
testing
tdd
broadcastreceiver
instrumentation
【解决方案1】:
BroadcastReceiver 的生命周期没有什么神奇之处。使用 AndroidTestCase 对其进行测试就足够了。在测试用例中,实例化您的 BroadcastReceiver,创建您想要发送的任何 Intent,并使用 AndroidTestCase 提供的 Context 或一些模拟 Context 调用 onReceive。
例如
public class TestMyBroadcastReceiver extends AndroidTestCase {
public void testReceive() {
MyBroadcastReceiver r = new MyBroadcastReceiver();
Intent i = new Intent("MY_ACTION");
// TODO put extras
r.onReceive(getContext(), i);
// TODO query application state to verify results
}
}