Espresso IntentsTestRule关于具有多个活动的测试

时间:2019-05-10 21:39:06

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

我正在尝试使用Espresso-Intents库对Android相机的结果进行存根分析。

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

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

问题在于,由于Espresso-Intents捕获了系统启动MainActivity的意图,因此MainActivity永远不会加载。

我收到此异常:

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-Intent捕获,并且我需要在同一@Test块中从MainActivity移至EditorActivity,因此如何在存入外部的同时允许一些内部Intent通过(例如,当EditorActivity调用时)在EditorActivity中触发的Camera API)?

谢谢你!

1 个答案:

答案 0 :(得分:1)

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

这就是说,如果您只想在@Test块中存根特定的Intent,则应在@Test块中的操作触发外部(针对您的应用实例)Intent(例如a)之前初始化Espresso-Intents。按钮以加载相机),并在返回存根后立即释放Espresso-Intent。

这是在对外部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();
}

希望您对此有帮助!

相关问题