为什么没有测试仪器的BroadcastReceiver的?测试仪器、BroadcastReceiver

2023-09-04 11:49:08 作者:Persistent慕拉

也许我失去了一些东西。我想要写测试用例一个BroadcastReceiver;具体地讲,它是用于接收BOOT_COMPLETED事件和设置为另一个接收到购买处理报警;它似乎并没有被正确设置它,但问题是,我没有任何明显的方法来测试它。我不能确切附加一个调试器,等待BOOT_COMPLETED,我不能发送假冒的BOOT_COMPLETED广播。

Maybe I'm missing something. I want to write test cases for a BroadcastReceiver; specifically, it is for receiving the BOOT_COMPLETED event and setting an alarm for another receiver to handle later; it doesn't seem to be setting it properly, but the point is that I have no obvious way to test it. I can't exactly attach a debugger and wait for BOOT_COMPLETED, and I can't send a fake BOOT_COMPLETED broadcast.

为什么有仪器仪表类的活动,服务和供应商,而不是BroadcastReceiver的?有什么建议给测试呢?

Why are there instrumentation classes for Activity, Service, and Provider, but not BroadcastReceiver? Any advice for testing this?

推荐答案

有什么魔力的生命周期中的BroadcastReceiver。这足以与AndroidTestCase测试。在测试案例,实例化你的BroadcastReceiver,创造任何意向要发送和通话的onReceive利用AndroidTestCase现有的上下文或一些模拟语境。

There is nothing magical about the life cycle for the BroadcastReceiver. It's enough to test it with an AndroidTestCase. In a test case, instantiate your BroadcastReceiver, create whatever Intent you want to send and call onReceive using the Context available from AndroidTestCase or some mock Context.

例如。

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
  }
}
 
精彩推荐