* {@link ServiceTestRule} is a JUnit rule that provides a * simplified mechanism to start and shutdown your service before * and after the duration of your test. It also guarantees that the service is successfully * connected when starting (or binding to) a service. The service can be started * (or bound) using one of the helper methods. It will automatically be stopped (or unbound) after * the test completes and any methods annotated with * After are * finished. *
After
* Note: This rule doesn't support {@link android.app.IntentService} because it's automatically * destroyed when {@link android.app.IntentService#onHandleIntent(android.content.Intent)} finishes * all outstanding commands. So there is no guarantee to establish a successful connection * in a timely manner. */ @MediumTest @RunWith(AndroidJUnit4.class) public class LocalServiceTest { @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); @Test public void testWithBoundService() throws TimeoutException { // Create the service Intent. Intent serviceIntent = new Intent(InstrumentationRegistry.getTargetContext(), LocalService.class); // Data can be passed to the service via the Intent. serviceIntent.putExtra(LocalService.SEED_KEY, 42L); // Bind the service and grab a reference to the binder. IBinder binder = mServiceRule.bindService(serviceIntent); // Get the reference to the service, or you can call public methods on the binder directly. LocalService service = ((LocalService.LocalBinder) binder).getService(); // Verify that the service is working correctly. assertThat(service.getRandomInt(), is(any(Integer.class))); } }