使用 DatePicker 记录 Espresso 测试

Recording an Espresso test with a DatePicker

测试记录器生成的代码在记录后立即失败运行。

原因是在录制时,我点击年份,弹出年份微调器,我向后滚动,然后 select 其中一年。记录器不捕获滚动。

在 Xcode 中,他们添加了一种滚动到项目的方法。我在 Espresso 中找不到类似的东西。

(使用 Android Studio 2.3。)

我已经很久没有使用记录器了,而是手写我的测试。

我使用以下行在 DatePicker 中设置日期:

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

PickerActions class is defined in the espresso-contrib 图书馆。将其添加到您的 gradle 文件中:

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

然后我在辅助方法中使用它,点击按钮打开 DatePickerDialog,设置日期并通过点击确定按钮确认:

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

注:本回答旨在补充

查看 Android 仪器测试的 Android 源代码示例,该测试打开 DatePickerDialog and selects a date, refer to the PickerActionsTest.java 文件。

该文件中的两行关键代码如下:

// Sets a date on the date picker widget
onView(isAssignableFrom(DatePicker.class)).perform(setDate(1980, 10, 30));

// Confirm the selected date. This example uses a standard DatePickerDialog
// which uses
// android.R.id.button1 for the positive button id.
onView(withId(android.R.id.button1)).perform(click());

正如@stamanuel 在他的回答中提到的,PickerActions.setDate(year:monthOfYear:dayOfMonth:) method is defined in the androidx.test.espresso:espresso-contrib 库。