Unable to start unbound service inside of Android JUnit 4 instrumented test

I met the same issue as you. When I searched the reason in Android reference of ServiceTestRule, I found the reason is so simple.

Note: This method only supports services that allow clients to bind to them. In other words, if your service onBind(Intent) method returns null then a TimeoutException will be thrown.

Therefore I changed my onBind() method to return a non-null binder.

@Override
public IBinder onBind(Intent i) {
    return new LocalBinder();
}

in which LocalBinder is defined as

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

Then the TimeoutException went away!

I guess the reason of test failure is that your test runner cannot bind the service under test. Although the service is running since you have started it in your case, but test runner cannot detect if the service is running. It has to flag your test case as failed.


Try this one

@Rule
public final ServiceTestRule mServiceRule = ServiceTestRule.withTimeout(60L, TimeUnit.SECONDS);