3

我正在使用ActivityInstrumentationTestCase2在我的 GUI 上进行自动黑盒测试。有没有办法点击一个对话框,或者在单元测试中获取属于该对话框的视图?

我能想出的唯一方法是保留对对话框的引用并让我的 Activity 实现一个 getter 方法来让测试用例访问对话框。有没有更好的方法不需要更改我的生产代码?

4

1 回答 1

4

是的,有一种更好的方法可以将 AlertDialogs 暴露给您的自动化代码,但您必须在生产代码中这样做。这将是值得的,因为它会让你的生活更轻松。让我解释。

您可以将 AlertDialogs 分配给 WeakHashMap 对象并轻松检索它们。这是如何 -

//Definition for WeakHashMap Object
WeakHashMap< Integer, Dialog > managedDialogs = new WeakHashMap< Integer, Dialog  >();

//Some alertdialog builder that needs to be exposed
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(YourActivity.this);
switch(id)
    {
case DIALOG:
    alertDialogBuilder.setTitle("some title")
    .setMessage("some message")
    .setPositiveButton("button text", Onclick activity)         
    .setNeutralButton("button text", Onclick activity)          
    .setNegativeButton("button text", Onclick activity)         
.setCancelable(true);

    AlertDialog dialog = alertDialogBuilder.create();

    //Assigning the value of this dialog to the Managed WeakHashMap
    managedDialogs.put(DIALOG, dialog);
    return dialog;
    }

现在在您的测试框架中,当您希望出现对话框时,只需执行 -

AlertDialog dialog = (AlertDialog) activity.managedDialogs.get(YourActivity.DIALOG);
于 2010-11-30T23:03:59.843 回答