Select Date from Calendar in Android Espresso

2020-07-06 06:37发布

问题:

I am testing an Android app with Espresso. I have an EditText widget with androidInputType=date. When I touch this control with my finger, a calendar pops up for me to select the date.

How do I automate this in Espresso? I've looked all over the place and I can't figure it out. typeText() certainly does not work.

回答1:

Original answered by me here, but in the scope of another question: Recording an Espresso test with a DatePicker - so I repost my adapted answer from there:

Use this line to set the date in a datepicker:

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

This uses the PickerActions which is part of the espresso support library - the espresso-contrib. To use it, add it like this to your gradle file (You 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'
}

Then you could create a helper method which clicks the view 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 your tests:

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