简体   繁体   中英

Recording an Espresso test with a DatePicker

The recorder produces code that promptly fails on being run after recording.

The reason is that while recording, I tap the year, the year spinner pops up and I scroll back, then select one of the years. The recorder does not capture the scrolling.

In Xcode, they added a method to scroll to the item. Could not find something akin in Espresso.

(Using Android Studio 2.3.)

I have not used the recorder in a long time and instead wrote my tests by hand, so not sure if this answer is of help to you.

I use this line to set the date in a datepicker:

onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));

The PickerActions is within a special espresso support library - the espresso-contrib - add it like this to your gradle file (I need several excludes to prevent compile errors due to mismatching support library version):

androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
    exclude group: 'com.android.support', module: 'appcompat'
    exclude module: 'support-annotations'
    exclude module: 'support-v4'
    exclude module: 'support-v13'
    exclude module: 'recyclerview-v7'
    exclude module: 'appcompat-v7'
}

I then use this in a helper method which clicks the button that opens the datepicker, sets the date and confirms it by clicking the ok button:

public static void setDate(int datePickerLaunchViewId, int year, int monthOfYear, int dayOfMonth) {
    onView(withParent(withId(buttonContainer)), withId(datePickerLaunchViewId)).perform(click());
    onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
    onView(withId(android.R.id.button1)).perform(click());
}

and then use it like this in my tests:

TestHelper.setDate(R.id.date_button, 2017, 1, 1); 
//TestHelper is my helper class that contains the helper method above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM