gpt4 book ai didi

android - 在 AndroidTestCase 中访问 AlertDialog

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:05 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com