I want to write instrumented tests for Android UI's toasts. But it seems my codes are not working. It can't catch the toast when it's actually displayed on phone. I think possibly issue with my toast Matcher.
Language: Kotlin, API 36, Compose UI
class SimpleToastMatcher : TypeSafeMatcher<Root>() {
override fun matchesSafely(root: Root): Boolean {
val type = root.windowLayoutParams.get().type
if (type == WindowManager.LayoutParams.TYPE_TOAST) {
return true
}
// For overlays that might be toasts (e.g., on API 30+)
// they are typically not focusable.
if (type == WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY) {
return !root.decorView.isFocusable && !root.decorView.isFocusableInTouchMode
}
return false
}
override fun describeTo(description: Description?) {
description?.appendText("is toast")
}
}
onView(withText(toastText))
.inRoot(SimpleToastMatcher())
.check(matches(isDisplayed()))
Expect the test to verify if the toast is displayed, but test fail because it can't detect toasts when it's actually shown on screen and timed out.