jeudi 23 novembre 2017

How to select a checkbox in an overflow menu with Espresso?

I'm writing tests for a UI with an overflow menu with checkboxes, as per the image below. I want to check the state of each checkbox, and toggle them, but I'm having trouble finding a way of matching them. The checkbox and its label are different views, so I can't match the checkbox with withText() and hasSibling() doesn't work either. Since the layout is generated by the menu framework I have no control over the ids of the checkboxes (they both have the id "checkbox").

This is what the menu looks like:

enter image description here

And this is my attempt at matching and toggling the checkbox. It fails with a NoMatchingViewException.

private static void toggleMenu(String label, boolean initial) {
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    ViewInteraction v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withText(label)), isCompletelyDisplayed()));
    if(initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    v.perform(click());
    openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
    v = onView(allOf(instanceOf(CheckBox.class), hasSibling(withText(label)), isCompletelyDisplayed()));
    if(!initial)
        v.check(matches(isChecked()));
    else
        v.check(matches(not(isChecked())));
    pressBack();
}




Aucun commentaire:

Enregistrer un commentaire