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();
The app runs fine and shows the alert dialog when I run it normally, but when I run it in an instrumented test, it crashes in builder.create at the first line:
        final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
with this exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
This closes the app and then the test fails because there isn't any activity:
android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?
This is a thread problem, but that's not what I expected based on an answer here:
To verify if dialog appears you can simply check if View with a text that present inside the dialog is shown:
onView(withText("dialogText")).check(matches(isDisplayed()));
I don't understand how I'm supposed to check if the text is displayed if the app crashes before the dialog is created.
EDIT:
    mActivityRule.launchActivity(intent);
    mActivityRule.getActivity().showOptionDialog();
    onView(withText(mActivityRule.getActivity().getString(R.string.dialogText))).check(matches(isDisplayed()));
 
     
    