Espresso is a UI automation tool for Android by Google and it is used for Black box testing.
Now we will see the basic the issues faced in the script of Espresso.
After recording the script in Espresso the issue arise in following manners:–
- When the object on which you are performing some action is not visible on the screen.
- When there are multiple objects with the same “ID” so there comes a “multiple match” error.
- While executing the script when the script is too fastly executing and unable to find the object on which the action to be performed.
So we will see these three issues and their solutions.
1. when the object is not visible on which you are performing some action then use “scroll to”.
1 |
onView(withId(R.id.fax)).perform(scrollTo(), replaceText("7887777"), ViewActions.closeSoftKeyboard()); |
In the following code “fax” is the id of the field in which we are replacing an text of “7887777” so if the field is not visible during execution of the script then due to “scroll to” it will scroll to the field which is not visible on the screen automatically.
2. When there are multiple objects with the same “ID” so there comes a “multiple match” error.
In this condition I had already given a solution in my previous blog which will work in recycler view i,e
https://mobikul.com/recycler-view-multiple-match-problem-in-espresso/
Now I had some new technique for this problem you can use this technique also which is called “custom matcher” in this we perform a custom match using the index value in which we define the index value of an object so that it will easily perform an action even with the same ID of multiple object.
Here is the code for that :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { return new TypeSafeMatcher<View>() { int currentIndex = 0; @Override public void describeTo(Description description) { description.appendText("with index: "); description.appendValue(index); matcher.describeTo(description); } @Override public boolean matchesSafely(View view) { return matcher.matches(view) && currentIndex++ == index; } }; } |
After defining this you can simply define the index value for an object by the following code.
1 |
onView(withIndex(withId(R.id.productImage), 2)).perform(click()); |
In this we defined the index value “2” in which it will perform an action only on “2nd” index even though multiple object will have the same ID .
3. While executing the script when the script is too fastly executing and unable to find the object on which the action to be performed.
For this simply use :-
1 2 3 4 5 6 |
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } |
Using “Thread.sleep” we can halt the screen for a while s that it can easily find out the object on which we are performing some action.
I had uploaded one video in which I had used all the defined approaches for executing the script smoothly.