Espresso:当我点击使用浓缩咖啡的商品时,我如何断言是否启动了特定活动

时间:2017-02-02 07:28:18

标签: android android-espresso

点击视图项后,如何在Espresso中声明活动?

onView(withId(com.example.android.notepad.R.id.XYZ)).perform(click());

2 个答案:

答案 0 :(得分:2)

在测试中你可能有这个:

@Rule
public ActivityTestRule<MyActivity> testRule = new ActivityTestRule<>(MyActivity.class);

然后你可以打电话:

testRule.getActivity()

获取Activity的实例。

刚才的电话

testRule.getActivity() instanceof MyActivity

答案 1 :(得分:1)

您应该模拟点击按钮的过程,然后测试堆栈顶部的活动是否是您正在寻找的活动

@RunWith(AndroidJUnit4.class)
public class YourTestClass{


    @Test
    public void testButton() {
        Espresso.onView(ViewMatchers.withId(R.id.yourButtonId)).perform(ViewActions.click());

        Assert.assertEquals(getActivityInstance().getClass(), YourActivityThatShouldStart.class);
    }

    private Activity getActivityInstance() {
        final Activity[] currentActivity = {null};
        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
            public void run() {
                Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                if (resumedActivities.iterator().hasNext()) {
                    currentActivity[0] = (Activity) resumedActivities.iterator().next();
                }
            }
        });

        return currentActivity[0];
    }

}

testButton 函数中,有两行,第一行是单击按钮,第二行是检查生成的活动

Espresso适用于主线程,所以很好