使用 Robolectric,如何测试一个将意图广播为响应的 IntentService?
假设以下类:
class MyService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("action"));
}
}
在我的测试用例中,我试图做这样的事情:
@RunWith(RobolectricTestRunner.class)
public class MyServiceTest{
@Test
public void testPurchaseHappyPath() throws Exception {
Context context = new Activity();
// register broadcast receiver
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// test logic to ensure that this is called
}
};
context.registerReceiver(br, new IntentFilter("action"));
// This doesn't work
context.startService(new Intent(context, MyService.class));
}
}
MyService 永远不会使用这种方法启动。我对 Robolectric 比较陌生,所以我可能遗漏了一些明显的东西。在调用 startService 之前我必须做某种绑定吗?我已经通过在上下文中调用 sendBroadcast 来验证广播是否有效。有任何想法吗?