【问题标题】:Espresso IntentsTestRule on Test with Multiple ActivitiesEspresso IntentsTestRule 上的多项活动测试
【发布时间】:2019-09-28 19:23:57
【问题描述】:

我正在尝试使用 Espresso-Intents 库删除 Android 相机的结果。

我知道要初始化 Espresso-Inents 库,我需要定义一个 IntentsTestRule。我已经根据我的测试进入的第一个 Activity 定义了规则,即 MainActivity.class,因此规则是这样编写的:

@Rule
public IntentsTestRule<MainActivity> mIntentsTestRules = new IntentsTestRule(MainActivity.class);

问题是 MainActivity 永远不会加载,因为系统 Intent 启动 MainActivity 正在被 Espresso-Intents 捕获..

我收到此异常:

java.lang.RuntimeException: Could not launch intent Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.greenpathenergy.facilitysurveyapp/.ui.activities.MainActivity } within 45 seconds.

此外,由于此 Intent 被 Espresso-Intents 捕获,并且我需要在同一个 @Test 块中从 MainActivity 移动到 EditorActivity,如何在存根外部 Intent 时允许一些内部 Intents 通过(例如当 EditorActivity 调用在 EditorActivity 中触发的 Camera API)?

谢谢!

【问题讨论】:

  • @Code-Apprentice 谢谢我下次会这样做,我已经提出了答案,如果不是最佳的,我不介意你批评。我发布的答案应该澄清最初的问题并表明我试图表达的真正意图(因为没有更好的词)。
  • IntentsTestRule 现在已被弃用..

标签: android android-intent android-espresso stub ui-testing


【解决方案1】:

IntentsTestRule 的目的是在运行 @Test 块中的任何测试之前单独初始化 Esspresso-Intents。 IntentsTestRule 只是在 @Test 块之前调用 Intents.init(),在 @Test 块完成之后调用 Intents.release()。

话虽这么说,如果您只想存根 @Test 块中的特定 Intent,则应在 @Test 块中触发外部(到您的应用程序实例)Intent(例如按钮单击以加载相机),并在我们返回存根后立即释放 Espresso-Intents。

这是在存根外部 Intent 的同时允许内部 Intent 的最简单的方法。

示例代码:

@Test
public void MainActivityTest {
   // Tap the button that loads the EditorActivity from MainActivity
   onView(withId(R.id.btn_load_editor_activity)).perform(click());

   // Initialize Espresso-Intents library to capture the external Intent to the camera API 
    Intents.init();

    // ActivityResult will be provided as a stub result for the camera API's natural result
    // Note: I've ignored the bitmap creation and instead used null for simplicity, you will
    // want to mock the bitmap here by creating a fake picture as the resultData
    ActivityResult result = new ActivityResult(Activity.RESULT_OK, null);

    // Notify Espresso the stub result above should be provided when it sees an Intent to load the camera API
    intending(toPackage("com.android.camera2")).respondWith(result);

    // Simulate a button tap of the button that loads the camera API, the stub will be automatically returned as the result immediately
    // instead of the camera API opening and sending back its result
    onView(withId(R.id.btn_take_placard_photo)).perform(click());

    // Release the Espresso-Intents library to allow other internal Intents to work as intended without being intercepted by Espresso-Intents
    Intents.release();
}

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    相关资源
    最近更新 更多