ShadowAlertDialog.getLatestAlertDialog()为android.support.v7.app.AlertDialog返回null

时间:2017-06-22 07:29:15

标签: android unit-testing android-testing robolectric

是否有任何解决方法可以让我们在 Robolectric 中测试android.support.v7.app.AlertDialog

   someActivity.findViewById(R.id.alet_btn).performClick();
   AlertDialog alert = ShadowAlertDialog.getLatestAlertDialog();
   ShadowAlertDialog shadowAlertDialog = Shadows.shadowOf(alert);
   assertThat(shadowAlertDialog.getTitle()).isEqualTo("Hello");

1 个答案:

答案 0 :(得分:0)

尝试以下

    List shownDialogs = ShadowAlertDialog.getShownDialogs();
    if (shownDialogs.get(0) instanceof AlertDialog) {
    AlertDialog dialog = (android.support.v7.app.AlertDialog) shownDialogs.get(0);
    assertThat(dialog).isShowing();
    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).performClick();
    }

    if (ShadowAlertDialog.getLatestDialog() instanceof AlertDialog) {
        AlertDialog dialog = (android.support.v7.app.AlertDialog) ShadowAlertDialog.getLatestDialog();
        assertThat(dialog).isShowing();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
    }

它允许您单击按钮,但不能验证标题或消息的AFAIK。