Select date from calendar in Android Espresso
I am testing an Android app using Espresso. I have a widget EditText
with androidInputType=date
. When I touch this control with my finger, the calendar is selected for me.
How do I automate this in Espresso? I have looked all over the place and I cannot figure it out. typeText()
certainly doesn't work.
source to share
The original was answered by me here, but within the scope of another question: Recording an Espresso test with a DatePicker - so I debug my adapted answer from there:
Use this line to set date in datepicker:
onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(year, monthOfYear, dayOfMonth));
Used here PickerActions
, which is part of the espresso support library - espresso-contrib
. To use it add it to your gradle file (you need a few exceptions to prevent compilation errors due to mismatch of 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'
}
Then you can create a helper method that clicks on the view, which opens the date, sets the date, and confirms it by clicking ok:
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 your tests:
TestHelper.setDate(R.id.date_button, 2017, 1, 1);
//TestHelper is my helper class that contains the helper method above
source to share