如何使用 Espresso 将时间设置为 MaterialDateTimePicker [英] How to set time to MaterialDateTimePicker with Espresso
问题描述
我正在尝试使用 Espresso 创建简单的 UI 测试来为新创建的项目设置日期.
Im trying to create simple UI test using Espresso to set a date to newly created item.
项目正在使用 https://github.com/wdullaer/MaterialDateTimePicker,但它显示对话框片段具有复杂的用户界面,没有什么可坚持的.
Project is using https://github.com/wdullaer/MaterialDateTimePicker, but it shows dialog fragment with complex UI and nothing to hold on to.
我想创建自定义 ViewAction 以设置类似于来自 Espresso 的 PickerActions 的日期或时间.
I would like to create custom ViewAction to set the date or time similar to PickerActions from Espresso.
有什么建议吗?
推荐答案
最后我创建了 ViewAction 也可以设置时间,但是它很麻烦,因为你必须知道对话框中视图的类名,有一些东西可以与 Matcher 相匹配.
In the end I've created ViewAction that is able to set the time too, but its messy, as you have to know classname of view in the dialog, to have something to match with Matcher.
/**
* Returns a {@link ViewAction} that sets a date on a {@link DatePicker}.
*/
public static ViewAction setDate(final int year, final int monthOfYear, final int dayOfMonth) {
return new ViewAction() {
@Override
public void perform(UiController uiController, View view) {
final DayPickerView dayPickerView = (DayPickerView) view;
try {
Field f = null; //NoSuchFieldException
f = DayPickerView.class.getDeclaredField("mController");
f.setAccessible(true);
DatePickerController controller = (DatePickerController) f.get(dayPickerView); //IllegalAccessException
controller.onDayOfMonthSelected(year, monthOfYear, dayOfMonth);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public String getDescription() {
return "set date";
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(DayPickerView.class), isDisplayed());
}
};
}
/**
* Returns a {@link ViewAction} that sets a time on a {@link TimePicker}.
*/
public static ViewAction setTime(final int hours, final int minutes) {
return new ViewAction() {
@Override
public void perform(UiController uiController, View view) {
final RadialPickerLayout timePicker = (RadialPickerLayout) view;
timePicker.setTime(new Timepoint(hours, minutes, 0));
}
@Override
public String getDescription() {
return "set time";
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isAssignableFrom(RadialPickerLayout.class), isDisplayed());
}
};
}
和用法:
onView(isAssignableFrom(DayPickerView.class)).perform(MaterialPickerActions.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)));
onView(isAssignableFrom(RadialPickerLayout.class)).perform(MaterialPickerActions.setTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
这篇关于如何使用 Espresso 将时间设置为 MaterialDateTimePicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!