如何对我的 Android 服务启动特定的 Activity 进行单元测试?
How can I unit test that my Android Service launched a particular Activity?
根据 this other question,可以从 Service
开始一个 Activity
。
如何在 ServiceTestCase
单元测试中将正确的 Intent
传递给 startActivity()
?
ActivityUnitTestCase
有好用的方法getStartedActivityIntent()
。我已经能够通过将 ContextWrapper
传递到其 setActivityContext()
方法来测试相反的情况——Activity
启动了 Service
——在 ActivityUnitTestCase
中,就像 this other question.
但是 ServiceTestCase
似乎没有 getStartedActivityIntent()
或 setActivityContext()
的等价物可以帮助我。我能做什么?
事实证明 the docs for ServiceTestCase
中的答案是正确的。
有是等同于setActivityContext()
,叫做setContext()
。因此,您可以调用 getContext()
,用 ContextWrapper
包裹上下文,然后调用 setContext()
,就像使用 ActivityUnitTestCase
一样。例如:
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;
}
根据 this other question,可以从 Service
开始一个 Activity
。
如何在 ServiceTestCase
单元测试中将正确的 Intent
传递给 startActivity()
?
ActivityUnitTestCase
有好用的方法getStartedActivityIntent()
。我已经能够通过将 ContextWrapper
传递到其 setActivityContext()
方法来测试相反的情况——Activity
启动了 Service
——在 ActivityUnitTestCase
中,就像 this other question.
但是 ServiceTestCase
似乎没有 getStartedActivityIntent()
或 setActivityContext()
的等价物可以帮助我。我能做什么?
事实证明 the docs for ServiceTestCase
中的答案是正确的。
有是等同于setActivityContext()
,叫做setContext()
。因此,您可以调用 getContext()
,用 ContextWrapper
包裹上下文,然后调用 setContext()
,就像使用 ActivityUnitTestCase
一样。例如:
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;
}