How to test for the appearance of a Toast message

前端 未结 9 1493
一生所求
一生所求 2020-12-16 09:55

Would anyone know how to test for the appearance of a Toast message on an Activity?

I\'m using code similar to what the OP posted on this question for testing my pro

9条回答
  •  没有蜡笔的小新
    2020-12-16 10:01

    For those now using the AndroidX Test API in 2019 and using a custom layout for toasts, try this (Kotlin):

    @RunWith(AndroidJUnit4:class)
    class ActivityUnitTest {
        private lateinit var scenario: ActivityScenario
    
        @Before fun setUp() {
            scenario = ActivityScenario.launch(MainActivity::class.java)
        }
    
        @Test fun shouldDisplayToastErrorMessageIfSearchFieldIsEmpty() {
            scenario.onActivity { activity ->
                activity.id_of_button.performClick()
                assertThat(
                    ShadowToast.getLatestToast().view.id_of_textview.text.toString(),
                    equalTo("Text to be tested")
                )
            }
        }
    }
    

提交回复
热议问题