Skip to content

Instantly share code, notes, and snippets.

@brunodles
Last active February 17, 2023 03:10
Show Gist options
  • Save brunodles/badaa6de2ad3a84138d517795f15efc7 to your computer and use it in GitHub Desktop.
Save brunodles/badaa6de2ad3a84138d517795f15efc7 to your computer and use it in GitHub Desktop.
This is a test to show how to use expresso to check if a toast was displayed.
package com.github.brunodles.toastespresso;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
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.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
@Test
public void shouldShowToast() {
onView(withText("Click on this button")).perform(click());
onView(withText(R.string.toast)).inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));
}
}
@nscherer
Copy link

nscherer commented Sep 3, 2018

Where does inRoot come from? I'm trying to use it and it isn't recognized. There is no import statement for it in this code, and so far I haven't found its location.

@coachroebuck
Copy link

FYI: inRoot() will be found in the the implementation of Espresso's ViewInteraction class.

Thanks for the share @brunodles!

@ChewBoonZhan
Copy link

Hey, wish to ask if my toast is previewed from a method like my_toast.show(), how do I verify it using testing? My toast don't show after a button is clicked, but more like when the my_toast.show() is called inside my app.

@dalewking
Copy link

Does not work in Android 30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment