Using Robolectric, how would one go about testing an IntentService that broadcasts intents as a response?
Assuming the following class:
class MyService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("action"));
}
}
In my test case, I’m attempting to do something like this:
@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 is never started using this approach. I’m relatively new to Robolectric, so I’m probably missing something obvious. Is there some sort of binding I have to do before calling startService? I’ve verified that broadcasting works by just calling sendBroadcast on the context. Any ideas?
You can’t test the service initialization like you’re trying to do. When you create a new activity under Robolectric, the activity you get back is actually a
ShadowActivity(kind of). That means when you callstartService, the method that actually gets executed is this one, which just calls intoShadowApplication#startService. This is the contents of that method:You’ll notice that it doesn’t actually try to start your service at all. It just notes that you attempted to start the service. This is useful for the case that some code under test should start the service.
If you want to test the actual service, I think you need to simulate the service lifecycle for the initialization bit. Something like this might work:
I’m not familiar with how Robolectric treats
BroadcastReceivers, so I left it out.EDIT: It might make even more sense to do the service creation/destruction in JUnit
@Before/@Aftermethods, which would allow your test to only contain theonStartCommandand “test test test” bits.