为什么没有BroadcastReceiver的测试仪器?
也许我错过了一些东西。我想为 BroadcastReceiver 编写测试用例;具体来说,它是为了接收BOOT_COMPLETED事件并设置警报以供另一个接收器稍后处理;它似乎没有正确设置,但重点是我没有明显的方法来测试它。我无法准确地附加调试器并等待 BOOT_COMPLETED,并且无法发送假的 BOOT_COMPLETED 广播。
为什么有 Activity、Service 和 Provider 的检测类,但没有 BroadcastReceiver?对于测试这个有什么建议吗?
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.
Why are there instrumentation classes for Activity, Service, and Provider, but not BroadcastReceiver? Any advice for testing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BroadcastReceiver 的生命周期并没有什么神奇之处。使用 AndroidTestCase 对其进行测试就足够了。在测试用例中,实例化您的 BroadcastReceiver,创建您想要发送的任何 Intent,并使用 AndroidTestCase 提供的 Context 或一些模拟 Context 调用 onReceive。
例如
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.
E.g.
对于大多数情况,我完全同意 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
For most cases I agree completely with https://stackoverflow.com/a/5181010/527016
There are however cases when extending
AndroidTestCase
is not suitable (and can cause surprises). In particular, if you are doing more complex integration testing and want to test yourBroadcastReceiver
with an actualIntent
sent by the system. The main reason is that theonReceive
method in the broadcast receiver runs on the main application thread while the tests inAndroidTestCase
run in another thread. This can cause test-related threading issues in code that was not intended to run on multiple threads.The solution to this is to subclass your test from
InstrumentationTestCase
instead and use the@UiThreadTest
annotation to make the tests run on the same thread as theonReceive
method.For more info (and an example) see: http://olafurhelgason.blogspot.com/2012/12/threading-and-android-integration.html