Android测试:如何查看屏幕上显示的对话框?(使用ActivityInstrumentationTestCase2)

Gui*_*ume 15 android unit-testing

我正在尝试最终将UI测试添加到我的Android应用程序中,以增加覆盖率(我所有其他层都经过适当测试,因此我的所有错误现在都来自UI ...)我开始使用ActivityInstrumentationTestCase2我的基类作为模拟器单元 - 测试,简单的事情很容易检查和工作.

但现在,我正在尝试按预期检查对话框,我不知道该怎么做.

我的测试:

public void testOpensAboutDialogWhenAboutButtonClicked() {
    final MyActivity activity = getActivity();
    final Instrumentation instrumentation = getInstrumentation();

    final Button aboutButton = (Button) activity.findViewById(R.id.about);
    TouchUtils.clickView(this, aboutButton);

    // how to test for the AboutDialog?
}
Run Code Online (Sandbox Code Playgroud)

现在我的对话框没有id,所以我无法使用findViewById获取指向它的指针.它是使用可用的构建器类创建的:

final AlertDialog about = new AlertDialog.Builder(parent)
            .setTitle(parent.getString(R.string.about_title))
            .setCancelable(true)
            .setIcon(R.drawable.skull)
            ....
Run Code Online (Sandbox Code Playgroud)

任何想法,或指向教程的指针?

编辑:要回答Jens评论,我没有使用托管对话框,只是创建AlertDialog并使用.show()显示它

Jen*_*ens 20

既然你已经在使用ActivityInstrumentationTestCase2你应该开始使用Robotium -这将简化测试了很多.

对于你的情况,它就像这样简单(如果你知道预期的标题或其他对你的对话有点模糊的话):

public void testSomeRandomSentence() {
    Solo solo = new Solo(getInstrumentation(), getActivity());
    getInstrumentation().waitForIdleSync();
    // Now do whatever you need to do to trigger your dialog.

    // Let's assume a properly lame dialog title.
    assertTrue("Could not find the dialog!", solo.searchText("My Dialog Title"));
}
Run Code Online (Sandbox Code Playgroud)