Gal Ben-Haim Gal Ben-Haim - 5 months ago 122
Android Question

How to test an IntentService with Robolectric?

I'm trying to test the

onHandleIntent()
method of an
IntentService
using
Robolectric
.

I'm starting the service with:

Activity activity = new Activity();
Intent intent = new Intent(activity, MyService.class);
activity.startService(intent);

ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
Intent startedIntent = shadowActivity.getNextStartedService();
assertNotNull(startedIntent);


seems like
startedIntent
is not null, but
onHandleIntent()
doesn't seem to be called.

how should I test it ?

Answer

onHandleIntent is a protected method so it can't be called directly.

my solution was to extend the service class in my test case, override onHandleIntent making it public and calling super(intent)

then call onHandleIntent directly from the test case.