13

也许我错过了一些东西。我想为 BroadcastReceiver 编写测试用例;具体来说,它用于接收BOOT_COMPLETED事件并设置警报以供另一个接收器稍后处理;它似乎没有正确设置它,但关键是我没有明显的方法来测试它。我不能完全附加调试器并等待 BOOT_COMPLETED,也不能发送虚假的 BOOT_COMPLETED 广播。

为什么有 Activity、Service 和 Provider 的检测类,但没有 BroadcastReceiver?对此有什么建议吗?

4

2 回答 2

20

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
  }
}
于 2011-03-03T13:01:02.023 回答
7

对于大多数情况,我完全同意https://stackoverflow.com/a/5181010/527016

然而,在某些情况下扩展AndroidTestCase不合适(并且可能导致意外)。特别是,如果您正在执行更复杂的集成测试并希望使用系统发送BroadcastReceiver的实际测试来测试您Intent的。主要原因是onReceive广播接收器中的方法在主应用程序线程上运行,而测试AndroidTestCase在另一个线程中运行。这可能会在不打算在多个线程上运行的代码中导致与测试相关的线程问题。

对此的解决方案是将您的测试从子类化,InstrumentationTestCase并使用@UiThreadTest注释使测试在与onReceive方法相同的线程上运行。

有关更多信息(和示例),请参阅: http: //olafurhelgason.blogspot.com/2012/12/threading-and-android-integration.html

于 2012-12-05T14:55:11.537 回答