[英]Is there a way to test pickers with Robolectric?
I was following the tutorial from Android developer. 我正在关注Android开发人员的教程。 Right now my class looks like this: 现在我的班级看起来像这样:
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
final Calendar calendar = Calendar.getInstance();
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new DatePickerDialog(getActivity(), this,
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
}
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
calendar.set(year, month, day);
Datable datable = (Datable) view.getContext();
datable.setDate(calendar.getTime());
}
}
If I try to run a test like the following, I'm getting a NullPointerException on the first getDataPicker()
. 如果我尝试运行如下所示的测试,我在第一个getDataPicker()
上得到一个NullPointerException。 I want to check that the default date is today. 我想检查默认日期是否为今天。
@Test
public void testDatePickerFragment() {
final Calendar calendar = Calendar.getInstance();
int expectedYear = calendar.get(Calendar.YEAR);
int expectedMonth = calendar.get(Calendar.MONTH);
int expectedDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerFragment fragment = new DatePickerFragment();
FragmentActivity activity = Robolectric
.buildActivity(FragmentActivity.class).create().start()
.resume().get();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragment.show(fragmentManager, "datePicker");
fragmentTransaction.commit();
DatePickerDialog dialog = (DatePickerDialog) ShadowDatePickerDialog
.getLatestDialog();
assertThat(dialog, is(not(nullValue())));
assertThat(dialog.getDatePicker().getDayOfMonth(), is(expectedDay));
assertThat(dialog.getDatePicker().getMonth(), is(expectedMonth));
assertThat(dialog.getDatePicker().getYear(), is(expectedYear));
}
I would like to be able to test this class without using it inside an activity (in that case I believe I can use the buildActivity
method and then ShadowDatePickerDialog
but that's the next step). 我希望能够在不在活动中使用它来测试这个类(在这种情况下,我相信我可以使用buildActivity
方法,然后使用ShadowDatePickerDialog
但这是下一步)。
So, is it possible to test the datePicker? 那么,是否可以测试datePicker? I'm using robolectric 2.2 我正在使用robolectric 2.2
It works with the new version Robolectric 3.X. 它适用于新版Robolectric 3.X. You can try something like this: 你可以尝试这样的事情:
startDate.performClick();
DatePickerDialog dialog = (DatePickerDialog) ShadowDatePickerDialog.getLatestDialog();
dialog.updateDate(2013, 10, 23);
dialog.getButton(DatePickerDialog.BUTTON_POSITIVE).performClick();
assertEquals("2013-11-23", startDate.getText().toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.