Home » Android » android – Test a TextView value is not empty using Espresso and fail if a TextView value is empty

android – Test a TextView value is not empty using Espresso and fail if a TextView value is empty

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am new to android Testing. I am trying to get the test to fail if the user clicks on a button and the TextView is empty. Is there a way to do this in espresso, so it will fail if the TextView is empty. I don’t want to check the TextView contain a specific text, i want to check that it is not empty.

How to&Answers:

Try this:

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;

@RunWith(AndroidJUnit4.class)
public class MainActivityInstrumentedTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule =
            new ActivityTestRule<>(MainActivity.class);

    @Test
    public void checkTextView_isDisplayed_and_notEmpty() throws Exception {
        // perform a click on the button
        onView(withId(R.id.button)).perform(click());

        // passes if the textView does not match the empty string
        onView(withId(R.id.textView)).check(matches(not(withText(""))));
    }
}

The test will only pass if the textView contains any text.