Android测试:如何使用ActivityInstrumentationTestCase2检查对话框是否显示在屏幕上?

16

我正在尝试为我的安卓应用添加UI测试,以增加测试覆盖率(我的所有其他层都已经得到了适当的测试,因此现在所有的漏洞都来自于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?
}

现在我的对话框没有ID,因此我无法使用findViewById获取指向它的指针。 它是使用可用的builder类创建的:

final AlertDialog about = new AlertDialog.Builder(parent)
            .setTitle(parent.getString(R.string.about_title))
            .setCancelable(true)
            .setIcon(R.drawable.skull)
            ....
任何想法或指向教程的指针?
编辑:回答Jens的评论,我没有使用托管对话框,只是创建AlertDialog并使用.show()显示它。

你正在使用托管对话框吗? - Jens
@Jens,实际上我不是,我甚至不知道它们的存在...我只是读了一些关于它们的文章,这可能确实有助于解决我的问题...(这会教训我不要跳过教程...)今晚会尝试。如果成功了,请写一个答案,这样我就可以给你奖励;) - Guillaume
我可以给你一个恰当的答案。 - Jens
3个回答

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"));
}

有趣。我会去查看它。 - Guillaume
好的,这看起来很有前途,绝对是我要走的路。恭喜你,你赢得了赏金! - Guillaume
1
当我使用Robotium时,这个方法对我并没有起作用。我认为问题可能是因为我使用的是旧式对话框(而不是“DialogFragment”),因此某种方式它不能像相同的方式连接到视图层次结构,所以solo.searchText(..)找不到它。通过使用“DialogFragment”并使用Robotium的solo.waitForFragmentByTag(...)方法进行修复 - 现在它已经很好地运作 :) - Dori

1

在setUp()中为Toast分配id后

toast = (Toast)activity.findViewById(..........);

创建测试用例() { }
ViewAsserts.assertOnScreen(toasts.getRootView(), toast.getRootView());
//pass if toast is visible on screen

}


谢谢你的回答,但它不是Toast,而是AlertDialog。我的问题的重点是它没有ID,所以我无法使用findViewById,并且我无法获取对话框的引用。 - Guillaume

0
在您的对话框中添加一个getter,例如:
public AlertDialog get_aboutbox()
{
   return this.about;
}

那么这里是您测试的解决方案:

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

    assertNotNull("aboutbox is null",activity.get_aboutbox());
    final Instrumentation instrumentation = getInstrumentation();

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

    assertTrue("About Button didn't displayed the Dlg",
               activity.get_aboutbox().isShowing());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接