点击视图项后,如何在Espresso中声明活动?
onView(withId(com.example.android.notepad.R.id.XYZ)).perform(click());
答案 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适用于主线程,所以很好