我有一个 Android 应用程序,其中启动 Activity 启动 IntentService。我想知道如何测试这个 Intent 是否已发送。我正在使用 Robolectric,但我才刚刚开始,所以如果需要我可以将其删除。
我的 onCreate 也根据是否加载了某些数据来显示一个 fragment 。这来自单例。我想知道如何测试该 fragment 是否显示。
最佳答案
测试服务
Intent
要测试 IntentService
,您的测试可以使用 Robolectric.getShadowApplication().getNextStartedService()
,它将返回用于启动的 Intent
对象服务。然后,您可以对 Intent 执行断言以验证操作是否符合预期。
@Test
public void shouldStartMyIntentService() throws Exception {
Intent serviceIntent = Robolectric.getShadowApplication().getNextStartedService();
assertEquals("MY_INTENT_ACTION", serviceIntent.getAction());
}
验证Fragment
是否可见
验证 fragment 是否可见的一个简单方法是对 fragment 中的 View 的包含 Activity
执行 findViewById
:
@Test
public void shouldShowPuppyFragment() throws Exception {
Activity activity = Robolectric.buildActivity(PuppyAndKittenActivity.class).create().visible().get();
assertEquals(View.VISIBLE, activity.findViewById(R.id.puppies).getVisibility());
assertNull(activity.findViewById(R.id.kittens));
}
旁注...
我强烈建议立即使用 Robolectric 2.2-SNAPSHOT 版本。自 2.1.1 发布以来,发生了很多非常好的更改,我不确定何时会发布新版本。 Robolectric 是一项持续不断的工作,并且正在定期改进。
关于Android 单元测试验证 OnCreate 是否发送 Intent 并显示该 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18796633/