使用 Espresso 测试 TextView 值不为空,如果 TextView 值为空则失败

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

我是 android 测试新手。如果用户单击按钮并且 TextView 为空,我试图让测试失败。有没有办法在浓缩咖啡中执行此操作,因此如果 TextView 为空,它将失败。我不想检查 TextView 是否包含特定文本,我想检查它是否不为空。

试试这个:

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(""))));
    }
}

只有当 textView 包含任何文本时,测试才会通过。