使用Robolectric从对话框片段测试日期选择器

时间:2019-03-26 03:13:22

标签: java android unit-testing robolectric

我想测试一下,当我单击EditText时,是从DatePicker创建的DialogFragment对话框中,打开并填写所选日期的EditText

我正在使用Robolectric,但Robolectric将对话框视为AlertDialog而不是DatePicker Dialog 这是错误消息:

java.lang.ClassCastException: android.app.AlertDialog cannot be cast to android.app.DatePickerDialog 

测试

@Test
public void endDateBeforeStartDateAlert() throws Exception {
    EditText endDate = activity.findViewById(R.id.end_date);
    endDate.performClick();
    DatePickerDialog dialog = (DatePickerDialog) ShadowDatePickerDialog.getLatestDialog();
    dialog.updateDate(2013, 10, 23);
    assertEquals("10/23/2013", endDate.getText().toString());
}

DatePickerDialog

public class PickDateDialog extends DialogFragment implements DialogInterface.OnClickListener{

public static final String TAG = "PickDateDialog";

//views
private DatePicker datePicker;

public PickDateDialog() {}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.createCallbackToParent();
}

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final DatePickerDialog.Builder datePickerDialog = new DatePickerDialog.Builder(getActivity());
    datePicker = new DatePicker(getActivity());
    datePickerDialog.setView(datePicker);
    datePickerDialog.setPositiveButton(getString(R.string.ok_button), this);
    datePickerDialog.setNegativeButton(getString(R.string.cancel_button), this);

    return  datePickerDialog.create();
}

 @Override
public void onClick(DialogInterface dialogInterface, int button) {
    if(button == BUTTON_POSITIVE){
        this.setDate();
        mCallback.onOkButtonListener(calendar, viewId);


    }
    if(button == BUTTON_NEGATIVE){
        dialogInterface.cancel();

    }

 }
}

关于如何测试DatePicker的任何想法? 谢谢您的时间

0 个答案:

没有答案