其他分享
首页 > 其他分享> > 在AndroidTestCase中访问AlertDialog

在AndroidTestCase中访问AlertDialog

作者:互联网

我正在使用ActivityInstrumentationTestCase2在我的GUI上执行自动黑盒测试.有没有一种方法可以单击对话框,或者在单元测试中获取属于该对话框的视图?

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

解决方法:

是的,有一种更好的方式将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);

标签:unit-testing,testing,automated-tests,instrumentation,android
来源: https://codeday.me/bug/20191106/2001210.html