【问题标题】: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
      }
    }
    

    【讨论】:

    • 简单而有效!
    【解决方案2】:

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

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

    解决方案是从InstrumentationTestCase 继承您的测试,并使用@UiThreadTest 注释使测试在与onReceive 方法相同的线程上运行。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2019-11-17
      • 1970-01-01
      • 2016-01-09
      相关资源
      最近更新 更多