如何测试Espresso中的活动之间的滑动?

时间:2016-05-23 05:54:07

标签: android testing android-espresso

我正在Espresso中创建一个测试,调用swipeRight()转到行为设置的MainActivity,然后返回ConsumerSettingsActivity来测试Views。但问题是,在调用滑动后,我得到一个NoActivityResumedException指向带有R.id.mode_text的第二个测试行。

@RunWith(AndroidJUnit4.class)
public class ConsumerSettingsActivityTest {

private ConsumerSettingsActivity mConsumerSettingsActivity;

@Rule
public ActivityTestRule<ConsumerSettingsActivity> mActivityTestRule =
        new ActivityTestRule<>(ConsumerSettingsActivity.class);

@Before
public void initialize() {
    mConsumerSettingsActivity = mActivityTestRule.getActivity();
}

@Test
public void checkCorrectButtonsAreClickableInPhotoModeThenReturnToMainActivity() {

    // swipe to MainActivity and set behavior
    onView(allOf(withId(R.id.settings_top_bar), isDisplayed())).perform(swipeRight());
    onView(withId(R.id.mode_text)).perform(click());
    onView(withId(R.id.photo_mode)).perform(click());


    // test ratio Views
    onView(withId(R.id.ratio_full)).check(matches(isClickable()));
    onView(withId(R.id.ratio_full)).perform(click());
    onView(withId(R.id.ratio_square)).check(matches(isClickable()));
    onView(withId(R.id.ratio_square)).perform(click()); 
...
}
}

1 个答案:

答案 0 :(得分:0)

简短回答:MainActivity在未创建的情况下被调用。

答案很长:当ConsumerSettingsActivity调用滑动更改为MainActivity时,实际滑动称为finish()。由于未创建MainActivity,因此抛出了NoActivityResumedException。要解决此问题,测试已更改为以MainActivity开头,然后将其滑动到ConsumerSettingsActivity。此外,我不需要让线程休眠以便能够在活动之间滑动。