Dharmaraj
Dharmaraj

Reputation: 184

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

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.

Upvotes: 11

Views: 8573

Answers (1)

chornge
chornge

Reputation: 2111

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.

Upvotes: 26

Related Questions