Service.startForeground () throws a NullPointerException when starting with ServiceTestCase

This one is a known annoying 2 year old Android bug.

My question is: does anyone know of a workaround for this problem besides changing the Android source code and compiling it again?

Here is my code to complete:

A subclass method of My Service that raises NPE:

/** Shows notification of started service */ private void doStartForeground() { // Prepare notification final NotificationHelper nh = doNotification("Service started"); // Start foreground startForeground(nh.getNotificationId(), nh.getNotification()); } 

This is called from overriding the onCreate() method.

And the JUnit testing method:

 public void test1() throws InterruptedException { assertTrue(context != null); final Intent service = new Intent(); service.setComponent(new ComponentName(CoreService.PACKAGE_NAME, CoreService.SERVICE_FULL_NAME)); IBinder binder = bindService(service); assertTrue(binder != null); } 

Stack trace:

 java.lang.NullPointerException at android.app.Service.startForeground(Service.java:631) at com.blablabla.android.core.CoreService.doStartForeground(CoreService.java:82) at com.blablabla.android.core.CoreService.onCreate(CoreService.java:149) at android.test.ServiceTestCase.bindService(ServiceTestCase.java:234) at com.blablabla.android.core.test.MainTest.test1(MainTest.java:37) at java.lang.reflect.Method.invokeNative(Native Method) 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) 

The service starts correctly and works fine when it does not start through Android JUnit.

+7
source share
1 answer

Finally, I added a new static field in my service:

 /** JUNIT - this is for testing purposes only */ public static boolean isJUnit = false; 

And check it in the onCreate() method:

 // Start the service as foreground (Android should not kill this // service) if (!isJUnit) { doStartForeground(); } 

Then I set this flag from JUnit setUp() :

 @Override protected void setUp() throws Exception { super.setUp(); // More setup MyServiceClass.isJUnit = true; } 

Not the most elegant solution, but it takes me out of the blockade.

+6
source

All Articles