[FIXED] How to test a Toast in a fragment

Issue

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

Here are the bones of my test

@RunWith(AndroidJUnit4:class)
class MyFragmentTest() {

    val displayToast = R.id.btn_toast

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

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

Error

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()))

error

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.

https://stackoverflow.com/a/42061993/3943340
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.

Solution

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.

@RunWith(RobolecticTestRunner::class)
class MyFragmentUnitTest {

    private lateinit var scenario: FragmentScenario<MyFragment>

    @Before
    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
        )
    }

    @Test
    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
        toastButton.perform(ViewActionsclick())

        val toastText = "This is my toast"
        assertEquals(ShadowToast.shoedToast(toastText))
    }
}

Answered By – Shawn

Answer Checked By – Laura B. (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published