android - 在 AndroidTestCase 中访问 AlertDialog

标签 android unit-testing testing automated-tests instrumentation

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

我能想出的唯一方法是保留对对话框的引用并让我的 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);

关于android - 在 AndroidTestCase 中访问 AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2306732/

相关文章:

ruby-on-rails - 在 Rails 中检索特定的固定装置

android - android taskaffinity的使用

android - 如何为 View 的属性设置动画

java - 单元测试以 ResultSet 作为参数的方法

testing - 如何在katalon studio中为测试api(restful)传递json参数?

testing - 集成和单元测试不再适用于无法在运行时找到程序集的 ASP.NET Core 2.1

android - 作业调度服务

Android声音池功能

java - 在 Spring TestContext 中使用 DbUnit 的问题

android - 使用 Espresso 进行相机操作 UI 测试