在Android Espresso中选择日历中的日期

时间:2017-03-31 21:11:51

标签: android android-espresso

我正在使用Espresso测试Android应用。我有一个EditText小部件androidInputType=date。当我用手指触摸此控件时,会弹出一个日历来选择日期。

如何在Espresso中自动执行此操作?我到处都看了,我无法理解。 typeText()肯定不起作用。

1 个答案:

答案 0 :(得分:15)

我原来在这里回答,但是在另一个问题的范围内:Recording an Espresso test with a DatePicker - 所以我从那里重新发布我的改编答案:

使用此行在datepicker中设置日期:

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

这使用了PickerActions,它是espresso支持库的一部分 - espresso-contrib。要使用它,请将它添加到您的gradle文件中(由于支持库版本不匹配,您需要多个排除以防止编译错误):

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'
}

然后你可以创建一个帮助方法,点击打开日期选择器的视图,设置日期并通过单击确定按钮确认它:

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());
}

然后在测试中使用它:

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