如何在碎片中测试Toast



如何创建一个测试来确认Toast显示在片段中。

这是我测试的要点

@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. 想法一
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. 想法2此示例需要自定义ToastMatcher
onToast("My Toast").check(matches(isDisplayed()))

错误

androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "No word entered"
  1. 想法三这个选项也使用自定义ToastMatcher,我已经为kotlin更新了它

https://stackoverflow.com/a/42061993/3943340编码米奇,youtube教程

Mitch Github 编码

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

返回以下错误

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

我已经坚持了一段时间,如果你有其他建议或我哪里出了问题,我会很感激的。

使用RobolectricTestRunner在测试活动中启动片段。要启动片段,请在@Before函数中创建一个FragmentScenario。在@Test趣味游戏中,使用ShadowToast测试吐司。

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

相关内容

  • 没有找到相关文章

最新更新