使用 DatePicker 记录 Espresso 测试

问题描述 投票:0回答:2

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

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

在 Xcode 中,他们添加了滚动到项目的方法。我在浓缩咖啡中找不到类似的东西。

(使用Android Studio 2.3。)

android android-espresso
2个回答
14
投票

我已经很长时间没有使用录音机了,而是用手写了我的测试。

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

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

PickerActions 类在 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

2
投票

注意:此答案旨在补充@stamanuel的答案

要查看 Android 仪器测试的 Android 源代码中打开 DatePickerDialog 并选择日期的示例,请参阅 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:) 方法是在 androidx.test.espresso:espresso-contrib 库中定义的。

© www.soinside.com 2019 - 2024. All rights reserved.