Validate your ArrayAdapter with Espresso test case


This tutorial is based on ArrayAdapter which returns custom object on getItem() function of the adapter.
In this demo our custom object is as follows.
(Note this things are in Recycler view or ArrayAdapter )

public static class HelloCustomList {
        private String label;
        private String subLabel;

        public HelloCustomList (String label, String subLabel) {
            this.label = label;
            this.subLabel = subLabel;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        public String getSubLabel() {
            return subLabel;
        }

        public void setSubLabel(String subLabel) {
            this.subLabel = subLabel;
        }
    }
private List<HelloCustomList> mylist;
public HelloCustomList getItem(int position) {
     //This returns custom object instead of Predefined Type such as int string etc.
     return mylist.get(position);
}    

Next.
First Create a TestingDemo java file in the Test Folder of your android project.


@RunWith(AndroidJUnit4.class)
@LargeTest
public class TestingDemo{

}


Now inside TestingDemo Class write the following testcase and supporting function.
@Test
    public void MyFirstTest() throws Exception{
//Just some ui latency
try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//This clicks on item where lable is set to "Whatever you Set in the Lable"
onData(withContent("Whatever you Set in the Lable"))
                    .inAdapterView(withId(R.id.your_id_to_listview))
                    .perform(click());
//Your validation is done now if any error occurs then it might be the case where the item is not in the list.
}


The following is a helper function which maps the custom return from getItem() of ArrayAdapter to the string which you want your test case to perform click.

public static Matcher<Object> withContent(final String content) {
        return new BoundedMatcher<Object, HelloCustomList>(HelloCustomList.class) {
            @Override
            public boolean matchesSafely(HelloCustomList myObj) {
                return myObj.getLabel().equals(content);
            }

            @Override
            public void describeTo(Description description) {
                //not needed for this tutorial
            }
        };
    }

Comments

Popular posts from this blog

Add/Set collection in Firestore with the Firebase Admin SDK : Python 🐍

Writing to external SD card in Android 5.0 and above

Add/Set array in Firestore with the Firebase Admin SDK : Python 🐍