Android 单元测试验证 OnCreate 是否发送 Intent 并显示该 fragment

标签 android unit-testing junit robolectric

我有一个 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/

相关文章:

java - 如何反转 SeekBar 值?

android - 如何更好地在 Android 上对 Looper 和 Handler 代码进行单元测试?

java - playframework 2.2 功能测试

junit - 手动 AtUnit 与 'Junit,JMock and GUICE' -?

javascript - Cordova + Angular + PushPlugin - 未触发回调

android - Android中的屏幕截图路径

java - 新的 JUnit 4.8.1 @Category 渲染测试套件是否几乎过时了?

java - 使用 Selenium 和 JUnit 解析 HTML 文档中的链接

java - SonarQube 组件覆盖率详细信息与 JUnitTest 报告 : How to avoid resource not found warning?

java - 使用 Retrofit 处理不一致的 API 响应