如何对我的Android服务启动特定活动进行单元测试?

时间:2015-06-28 00:55:55

标签: android android-intent android-activity android-service android-testing

根据this other question,可以从Activity开始Service

如何在ServiceTestCase单元测试中将正确的Intent传递给startActivity()

ActivityUnitTestCase有一个有用的方法getStartedActivityIntent()。我已经能够通过将Activity传递到Service ActivityUnitTestCaseContextWrapper setActivityContext()ServiceTestCase getStartedActivityIntent()方法,如this other question

但是setActivityContext()似乎没有{{1}}或{{1}}的等价物来帮助我。我该怎么办?

1 个答案:

答案 0 :(得分:2)

原来答案是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;
}