Search code examples
android-espressogettext

How do I 'extract' text from ID?


In my test,

I check the text in the header for each page that I land.

I can match the text to “Sign In” (in R.id.toolbar_text) for example and see if it pass or fail. But, I would like to know if it failed, what is the text that I have in R.id.toolbar_text object.

Is the option getText() available in Espresso Android?

How do I 'extract' text from ID?


Solution

  • Here is an equivalent implementation in Java for getText():

    public static String getText(final Matcher<View> matcher) {
            try {
                final String[] stringHolder = {null};
                onView(matcher).perform(new ViewAction() {
                    @Override
                    public Matcher<View> getConstraints() {
                        return isAssignableFrom(TextView.class);
                    }
    
                    @Override
                    public String getDescription() {
                        return "get text";
                    }
    
                    @Override
                    public void perform(UiController uiController, View view) {
                        TextView tv = (TextView) view;
                        stringHolder[0] = tv.getText().toString();
                    }
                });
                if (stringHolder[0] == null || stringHolder[0] == "") {
                    fail("no text found");
                }
                return stringHolder[0];
            } catch (Exception e) {
                fail("null found");
                return null;
            }
    
        }