Maxwell
Maxwell

Reputation: 6822

Android ServiceTestCase: Context Package Name is null

I have a service that I'm trying to unit test using ServiceTestCase. In my setUp(), I'm creating the IBinder, but I get a NullPointerException when creating the intent. I'm using the application's context and setting it to the test case, but the package name seems to be null. Any ideas as to why it's doing this and what the solution might be?

ServiceTestCase Code:

public class MyActivityTest extends ServiceTestCase<ImageDownloadTaskService> {

ImageDownloadTaskService service;

/**
 * Constructor
 */
public MyActivityTest() {
    super(ImageDownloadTaskService.class);
}

@Override
protected void setUp() throws Exception {
    super.setUp();
    setApplication(new MyApplication());
    getApplication().onCreate();
    setContext(getApplication());
    Intent intent = new Intent(getContext(), ImageDownloadTaskService.class);
    IBinder binder = bindService(intent);
    service = ((ImageDownloadTaskService.LocalBinder) binder).getService();
}

public void testService(){
    assertTrue(service.returnTrue());
}
}

Service code snippet:

public boolean returnTrue(){
    return true;
}

public class LocalBinder extends Binder {
    ImageDownloadTaskService getService() {
        return ImageDownloadTaskService.this;
    }
}

private final IBinder binder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
    return binder;
}

Error:

java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3004)
at com.example.untitled2.MyActivityTest.setUp(MyActivityTest.java:43)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)

Upvotes: 2

Views: 2327

Answers (1)

Shobhit Puri
Shobhit Puri

Reputation: 26007

Try using getSystemContext() instead of getContext(). Docs say:

It returns the real system context that is saved by setUp(). Use it to create mock or other types of context objects for the service under test.

Hope this helps.

Upvotes: 3

Related Questions