I'm using ActivityInstrumentationTestCase2 to do automated black-box testing on my GUI. Is there a way to click on a dialog, or get Views belonging to the Dialog in unit tests?
The only way I could come up with is to keep a reference to the dialog and have my Activity implement a getter method to let testcases access the dialog. Is there a better way that doesn't require changing my production code?
Yes, there is a better way of exposing the AlertDialogs to your automation code but you WILL have to do that in the production code. It will be worth it though cause it will make your life a lot easier. Let me explain.
You can assign your AlertDialogs to a WeakHashMap object and retrieve them very easily. Here is how -
//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;
}
Now in your test framework, when you expect the dialog to appear, simply do -
AlertDialog dialog = (AlertDialog) activity.managedDialogs.get(YourActivity.DIALOG);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With