How to check expected intent sent without actually launching activity in Espresso?

前端 未结 3 1496
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 01:42

I have a UI test which clicks a button, and then launch a new Activity in its onClickListener. The test checks whether expected intent is sent or not.

My problem is, I w

3条回答
  •  无人及你
    2021-02-14 01:59

    Espresso's Intents class is a concise and handy api, but when it doesn't meet your needs, there is an alternative. If you use AndroidJUnit4 test runner, you can get Instrumentaion instance using InstrumentationRegistry.getInstrumentation(), and then you can add Instrumentation.ActivityMonitor instance.

    Instrumentation.ActivityMonitor am = new Instrumentation.ActivityMonitor("YOUR_ACTIVITY", null, true);
    InstrumentationRegistry.getInstrumentation().addMonitor(am);
    onView(withId(R.id.view_id_to_perform_clicking)).check(matches(isDisplayed())).perform(click());
    assertTrue(InstrumentationRegistry.getInstrumentation().checkMonitorHit(am, 1));
    

    The third parameter of ActivityMonitor constructor tells we want to block activity launching. Note that this approach has its limitation. In contrast to Espresso Intents' rich Matcher support, You can not set multiple condition for ActivityMonitor.

    You can find several samples in ApiDemos, especially in ContactsSelectInstrumentation class.

提交回复
热议问题