在Android Espresso中从日历中选择日期 [英] Select Date from Calendar in Android Espresso
问题描述
我正在用Espresso测试一个Android应用.我有一个带有androidInputType=date
的EditText
小部件.当我用手指触摸此控件时,会弹出一个日历供我选择日期.
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.
如何在Espresso中自动执行此操作?我到处都看了看,看不出来. typeText()
当然不起作用.
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.
推荐答案
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));
这使用了PickerActions
,它是espresso支持库的一部分-espresso-contrib
.要使用它,请将其添加到gradle文件中(您需要几个排除项,以防止由于支持库版本不匹配而导致编译错误):
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
这篇关于在Android Espresso中从日历中选择日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!