Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ServiceTestCase for IntentService

I'm currently writing unit tests for an android application and stumbled into the following issue:

I use the ServiceTestCase to test an IntentService like this:

@Override
public void setUp() throws Exception {
    super.setUp();      
}

public void testService()
{
    Intent intent = new Intent(getSystemContext(), MyIntentService.class);
    super.startService(intent);     
    assertNotNull(getService());        
}

However I noticed that my IntentService is created (means that onCreate is called) but I never receive a call into onHandleIntent(Intent intent)

Has anyone already tested an IntentService with the ServiceTestCase class?

Thanks!

like image 767
Dominik Helleberg Avatar asked Jul 12 '11 15:07

Dominik Helleberg


1 Answers

This is a bit late, but I just struggled with this. You could solve this by creating a class that simply overrides the onStart of you service so it calls onHandleIntent directly. So for instance, if you have a LocationUpdaterService, you could create a fake class that overrides the onStart function like this:

public class LocationUpdaterServiceFake extends LocationUpdaterService {

@Override
public void onStart(Intent intent, int startId) {
    onHandleIntent(intent);
    stopSelf(startId);
}

LocationUpdaterService is a subclass of IntentService, so when you write your tests, just use the LocationUpdaterServiceFake class like this

public class LocationUpdateServiceTest extends ServiceTestCase<LocationUpdaterServiceFake> {

public LocationUpdateServiceTest()
{
    super(LocationUpdaterServiceFake.class);
}

public void testNewAreaNullLocation()
{
    Intent intent = new Intent();
    intent.setAction(LocationUpdaterService.ACTION_NEW_AREA);

    startService(intent);
}

}

Now whenever you call startService, it will bypass the threading code in IntentService and just call your onHandleIntent function

like image 56
Matt J Avatar answered Oct 13 '22 18:10

Matt J