[FIXED] How to test a Toast in a fragment


How do you create a Test that confirms a Toast is displayed in a fragment.

Here are the bones of my test

class MyFragmentTest() {

    val displayToast = R.id.btn_toast

    fun setup() {
        launchFragmentInContainer<MyFragment>(null, R.style.My_Theme)

    fun displayToast() {
        // Insert different ideas here to display toast. 
  1. Idea one
onView(WithText("My Toast").check(matches(isDispalyed)))


androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131755008>[Toast_no_word] value: No word entered
  1. Idea 2
    This example requires a custom ToastMatcher, ToastMatcher
onToast("My Toast").check(matches(isDisplayed()))


androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "No word entered"
  1. Idea three
    This option also uses custom ToastMatcher, I’ve updated it for kotlin.

Coding with Mitch, youtube tutorial

Coding with Mitch Github

onView(withText("My Toast")).inRoot(TOastMatcher()).check(matches(isDisplayed()))

Returns the following error

androidx.test.espresso.NoMatchingRootException: Matcher 'is toast' did not match any of the following roots: [Root{application-window-token=android.view.ViewRootImpl$W@6b8a33b, window-e

I’ve been stuck on this for a while if you have an alternative suggestion or an idea of where I’ve gone wrong it would be apprecaited.


Use the RobolectricTestRunner to launch a fragment in a test Activity. To launch the fragment create a FragmentScenario in a @Before function. In a @Test fun use ShadowToast to test the toast.

class MyFragmentUnitTest {

    private lateinit var scenario: FragmentScenario<MyFragment>

    fun setup() {

        val viewModel: MyViewModel = mock(MyViewModel::class.java)

        // Your scenario may not need to include all this information. 
        scenario = launchFragmentInContainer(
            factory = MyFragmentFactory(viewModel),
            fragmentArgs = null,
            themeResId = R.style.Theme_mine

    fun `show toast`() {
        // Reference the button that will display the toast. 
        val toastButton = onView(ViewMatchers.withId(R.id.button_toast))
        // perform a click on the button

        val toastText = "This is my toast"

Answered By – Shawn

Answer Checked By – Laura B. (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published