@Test
    public void testWithBoundService() throws TimeoutException {
        // Create the service Intent.
        Intent serviceIntent =
                new Intent(getApplicationContext(), 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)));
    }
JUnit4 test that uses a {@link ServiceTestRule} to interact with a bound service.
<p>
{@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
<a href="http://junit.sourceforge.net/javadoc/org/junit/After.html"><code>After</code></a> are
finished.
<p>
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.
integration/ServiceTestRuleSample/app/src/androidTest/java/com/example/android/testing/ServiceTestRuleSample/LocalServiceTest.java