Access AlertDialog in AndroidTestCase

I use ActivityInstrumentationTestCase2 to automatically test a black box in my GUI. Is there a way to click on a dialog box or get views belonging to the dialog in unit tests?

The only way I could come up with is to save the link to the dialog and force My Activity to implement the getter method to allow the test windows to access the dialog. Is there a better way that does not require changing my production code?

+3
source share
1 answer

Yes, there is a better way to expose AlertDialogs for your automation code, but you have to do this in production code. It will be worth it because it will make your life a lot easier. Let me explain.

You can assign your AlertDialogs to a WeakHashMap object and get them very easily. Here's 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 the test environment, when you are waiting for the dialog to appear, just do -

AlertDialog dialog = (AlertDialog) activity.managedDialogs.get(YourActivity.DIALOG);
+4
source

Source: https://habr.com/ru/post/1733772/


All Articles