How can I unit test my Android service to trigger a specific event?
As per this other question, one can run Activity
from Service
.
How can I in ServiceTestCase
, unit test pass correct Intent
in startActivity()
?
ActivityUnitTestCase
has a useful method getStartedActivityIntent()
. And I was able to check the opposite that I Activity
ran Service
-v ActivityUnitTestCase
by passing ContextWrapper
in my setActivityContext()
method, like this other question .
But ServiceTestCase
doesn't seem to have any equivalents for getStartedActivityIntent()
or setActivityContext()
, which would help me here. What can I do?
source to share
Turns out the answer to the docs forServiceTestCase
.
There is an equivalent setActivityContext()
and it's called setContext()
. This way you can call getContext()
, wrap the context with, ContextWrapper
and call setContext()
like with 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;
}
source to share