Wednesday, 24 May 2017

Esspresso Custom Matchers

Esspresso Custom Matchers


private static Matcher<View> childAtPosition(
       
final Matcher<View> parentMatcher, final int position) {

   
return new TypeSafeMatcher<View>() {
       
@Override
       
public void describeTo(Description description) {
            description.appendText(
"Child at position " + position + " in parent ");
           
parentMatcher.describeTo(description);
        }

       
@Override
       
public boolean matchesSafely(View view) {
            ViewParent parent = view.getParent();
           
return parent instanceof ViewGroup && parentMatcher.matches(parent)
                    && view.equals(((ViewGroup) parent).getChildAt(
position));
        }
    };
}


Points to remember:

1.       ChildAtPosition is a custom Matcher view created above
2.       Custom view matcher requires two attributes which will be verified
a.       parentMatcher ( resource-id of parent.  Eg..  R.id.YourIDName)
b.      Child Position (which is the Index position of child )
3.       TypeSafeMatcher.matchesSafely() simply returns Boolean value if the parent is instanceof ViewGroup
4.       TypeSafeMatcher.describeTo() is simply used for debugging in console

How to use childAtPosition Matcher

Sample view from UIAutomatorViewer :



Child ID : miniBtnFour : Index : 3
Parent_One ID : fragmentCountingMenu : 0
Parent of Parent_One ID : nav_menu_fragment : 2

Code to Integrate:


ViewInteraction button77 = onView(
        allOf(withId(R.id.miniBtnFour),withText("Submit"),
                childAtPosition(
                        childAtPosition(
                               withId(R.id.nav_menu_fragment),0),
                        3),
                isDisplayed()));
button77.check(matches(withText("Submit")));
button77.perform(click());