51

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()));
SleepingLlama
  • 528
  • 1
  • 4
  • 8

3 Answers3

107

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)))
Benoit Duffez
  • 11,839
  • 12
  • 77
  • 125
ksarmalkar
  • 1,884
  • 1
  • 16
  • 21
  • 1
    What do you do when espresso do the check at the time snackbar's `Y` position is `0.0`? `isDisplayed` throws exception. – Christopher Francisco Feb 03 '16 at 22:00
  • make sure you do don't add this assert when y position is 0.0, this means either your snackbar is done showing or yet to show. you might need to adjust the test to make sure you either wait until its shown or check a bit earlier depends on your scenario – ksarmalkar Feb 05 '16 at 15:03
  • @ksarmalkar How should we wait for this, then? – AdamMc331 Nov 21 '16 at 17:18
  • One way would be to add your own matcher that polls every few millis with a max timeout so that it does not run indefinitely. pretty sure there might be lots of other ways to handle this. few come to mind, add a listener for snackbar dismiss and fail in case the dismiss is never invoked indicating the snackbar was never shown. – ksarmalkar Nov 22 '16 at 14:56
  • 11
    I get `NoMatchingViewException: No views in hierarchy found matching: with id: com.my.package.debug:id/snackbar_text` with this. Any ideas? – Chisko Mar 02 '18 at 19:28
  • your snackbar is probably hiding before this is asserted, maybe try adding more delay to hiding snackbar and see if it works – ksarmalkar Mar 12 '18 at 13:56
  • @ksarmalkar , How did you find this : `onView(withId(com.google.android.material.R.id.snackbar_text)) .check(matches(withText(R.string.whatever_is_your_text)))` – milad salimi Aug 08 '19 at 07:55
16

An alternative

private void checkSnackBarDisplayedByMessage(@StringRes int message) {
    onView(withText(message))
            .check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
Minuel
  • 161
  • 1
  • 5
2

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()));
}
Rizwan
  • 1,461
  • 12
  • 26