我正在关注Android开发人员的教程。现在我的班级看起来像这样:
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());
}
}
如果我尝试运行如下所示的测试,我会在第一个getDataPicker()
. 我想检查默认日期是今天。
@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));
}
我希望能够在不在活动中使用它的情况下测试这个类(在这种情况下,我相信我可以使用该buildActivity
方法,ShadowDatePickerDialog
但这是下一步)。
那么,是否可以测试 datePicker?我正在使用 robolectric 2.2