Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recording an Espresso test with a DatePicker

The test 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, I scroll back and then select one of the years. The recorder does not capture the scrolling.

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

(Using Android Studio 2.3.)

like image 658
Rob Avatar asked Dec 15 '22 00:12

Rob


1 Answers

I have not used the recorder in a long time and instead wrote my tests by hand.

I use the following line to set the date in a DatePicker:

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

The PickerActions class is defined in the espresso-contrib library. Add it as follows to your gradle file:

androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.4.0'

I then use this in a helper method which clicks the button that opens a DatePickerDialog, 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 in my tests as follows:

TestHelper.setDate(R.id.date_button, 2017, 1, 1); 
//TestHelper is my helper class that contains the helper method above
like image 159
stamanuel Avatar answered Dec 27 '22 11:12

stamanuel