How To Get Text From Textview Using Espresso
Solution 1:
The basic idea is to use a method with an internal ViewAction
that retrieves the text in its perform method. Anonymous classes can only access final fields, so we cannot just let it set a local variable of getText()
, but instead an array of String is used to get the string out of the ViewAction
.
String getText(final Matcher<View> matcher) {
final String[] stringHolder = { null };
onView(matcher).perform(newViewAction() {
@Overridepublic Matcher<View> getConstraints() {
return isAssignableFrom(TextView.class);
}
@Overridepublic String getDescription() {
return"getting text from a TextView";
}
@Overridepublicvoidperform(UiController uiController, View view) {
TextViewtv= (TextView)view; //Save, because of check in getConstraints()
stringHolder[0] = tv.getText().toString();
}
});
return stringHolder[0];
}
Note: This kind of view data retrievers should be used with care. If you are constantly finding yourself writing this kind of methods, there is a good chance, you're doing something wrong from the get go. Also don't ever access the View outside of a ViewAssertion
or ViewAction
, because only there it is made sure, that interaction is safe, as it is run from UI thread, and before execution it is checked, that no other interactions meddle.
Solution 2:
If you want to check text value with another text, you can create Matcher. You can see my code to create your own method:
publicstatic Matcher<View> checkConversion(finalfloat value){
returnnewTypeSafeMatcher<View>() {
@OverrideprotectedbooleanmatchesSafely(View item) {
if(!(item instanceof TextView)) returnfalse;
floatconvertedValue= Float.valueOf(((TextView) item).getText().toString());
floatdelta= Math.abs(convertedValue - value);
return delta < 0.005f;
}
@OverridepublicvoiddescribeTo(Description description) {
description.appendText("Value expected is wrong");
}
};
}
Post a Comment for "How To Get Text From Textview Using Espresso"