How can I unit test that my Android Service launched a particular Activity?

Issue

According to this other question, it is possible to start an Activity from a Service.

How can I, in a ServiceTestCase, unit test that the correct Intent is passed to startActivity()?

ActivityUnitTestCase has the useful method getStartedActivityIntent(). And I’ve been able to test the converse—that an Activity started a Service—in an ActivityUnitTestCase by passing a ContextWrapper into its setActivityContext() method, like in this other question.

But ServiceTestCase seems to have no equivalents for getStartedActivityIntent() or setActivityContext() that would help me here. What can I do?

Solution

Turns out the answer is right in the docs for ServiceTestCase.

There is an equivalent to setActivityContext(), and it’s called setContext(). So you can call getContext(), wrap the context with a ContextWrapper, and call setContext(), just like with an ActivityUnitTestCase. For example:

private volatile Intent lastActivityIntent;

@Override
protected void setUp() throws Exception {
    super.setUp();
    setContext(new ContextWrapper(getContext()) {
        @Override
        public void startActivity(Intent intent) {
            lastActivityIntent  intent;
        }
    });
}

protected Intent assertActivityStarted(Class<? extends Activity> cls) {
    Intent intent  lastActivityIntent;
    assertNotNull("No Activity started", intent);
    assertEquals(cls.getCanonicalName(), intent.getComponent().getClassName());
    assertTrue("Activity Intent doesn't have FLAG_ACTIVITY_NEW_TASK set",
            (intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) ! 0);
    return intent;
}

Answered By – Dan Getz

Leave a Comment