SleepingLlama
SleepingLlama

Reputation: 548

Testing Snackbar show with Espresso

Is there a way to test using Espresso that the snackbar shows up with the right text?

I have a simple call to create a snackbar

Snackbar.make(mView, "My text", Snackbar.LENGTH_LONG).show();

I have tried this without luck

onView(withText("My text")).inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));

Upvotes: 53

Views: 17171

Answers (3)

Minuel
Minuel

Reputation: 161

An alternative

private void checkSnackBarDisplayedByMessage(@StringRes int message) {
    onView(withText(message))
            .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}

Upvotes: 16

ksarmalkar
ksarmalkar

Reputation: 1894

This worked for me, please try.

onView(allOf(withId(android.support.design.R.id.snackbar_text), withText("My text")))
            .check(matches(isDisplayed()));

If you use AndroidX, please use the following:

onView(withId(com.google.android.material.R.id.snackbar_text))
        .check(matches(withText(R.string.whatever_is_your_text)))

Upvotes: 108

Rizwan
Rizwan

Reputation: 1662

I saw the previous answers but I thought this would be better.

@Test
public void onFabClick_shouldDisplaySnackbar() throws Exception {
  onView(withId(R.id.fab)).perform(click());

  // Compare with the text message of snackbar
  onView(withText(R.string.snackbar_message))
      .check(matches(isDisplayed()));
}

Upvotes: 3

Related Questions