3

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?

Community
  • 1
  • 1
Dan Getz
  • 7,743
  • 6
  • 29
  • 60

1 Answers1

2

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;
}
Dan Getz
  • 7,743
  • 6
  • 29
  • 60
  • So this was just a silly mistake of mine to not notice the obviously-named `setContext()` method, but I guess I'll leave it up in case it helps someone else. – Dan Getz Jun 28 '15 at 01:14