繁体   English   中英

警报对话框崩溃Android测试 - “无法在未调用Looper.prepare()的线程内创建处理程序”

[英]Alert Dialog crashes Android test - “Can't create handler inside thread that has not called Looper.prepare()”

    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage(message)
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    login(activity);
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    dialog.cancel();
                    activity.finish();
                }
            });
    AlertDialog alert = builder.create(); // Crash
    alert.show();

应用程序正常运行并在我正常运行时显示警告对话框,但是当我在检测测试中运行它时,它在第一行的builder.create中崩溃:

        final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);

有这个例外:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

这会关闭应用程序然后测试失败,因为没有任何活动:

android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?

这是一个线程问题,但这不是我所期望的基于这里的答案:

要验证是否显示对话框,您只需检查是否显示带有对话框内文本的View:

onView(withText("dialogText")).check(matches(isDisplayed()));

我不明白如果应用程序在创建对话框之前崩溃,我应该检查文本是否显示。

编辑:

    mActivityRule.launchActivity(intent);

    mActivityRule.getActivity().showOptionDialog();

    onView(withText(mActivityRule.getActivity().getString(R.string.dialogText))).check(matches(isDisplayed()));

一些可能对你有帮助的事情......

  1. 调用mActivityRule.getActivity().showOptionDialog(); 在Espresso测试中,不是'Espresso'方式。 除非你的测试被正确注释,否则它不会在UI线程上运行,所以这是一个你应该在Instrumentation线程的UI线程上调用的东西。 你可以通过以下方式解决这个问题:

    rule.runOnUiThread(new Runnable(){@Override public void run(){mActivityRule.getActivity()。showOptionDialog();}});

执行此操作可能需要您构建自己的同步逻辑,以确保在此之前未运行未来的Espresso语句。

使用Espresso测试此方法的更好方法是在UI控件上使用onView(XXX).perform(click()) ,通常会调用showOptionsDialog()

  1. 此外,您不需要自己解析传递给withText()的字符串,您只需使用字符串资源ID,但这不是您所看到的问题的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM