espresso 如何检查对话框是否不可见

espresso how do you check if a dialog isn't visible

我有一个测试来检查对话框是否存在。

@Test
fun dismissedWhenClicked() {
    //dimiss dialog
    onView(withText(R.string.simple)).inRoot(isDialog()).perform(click())
    //check dialog
    onView(isRoot()).inRoot(isDialog()).check(matches(not(isDisplayed())))
}

以上是我最好的猜测,但失败了,因为 Matcher 'is dialog' did not match any of the following roots

我在这里找到了 3 个问题,但 none 似乎解决了它。

Espresso check if no dialog is displayed - 评论有效,但在有对话框时也会通过

- 这不会检查,相反它会优雅地失败,我想。

espresso: Assert a Dialog is not shown - 似乎没有答案。

我已经用自定义匹配器解决了这个问题modified slightly from here

@Test
    fun dismissedWhenClicked() {
        onView(withText(R.string.simple)).inRoot(isDialog()).perform(click())
        onView(withId(R.id.fragment_layout)).inRoot(Utils.ActivityMatcher()).check(matches(isDisplayed()))
    }
class ActivityMatcher : TypeSafeMatcher<Root>() {
        override fun describeTo(description: Description) {
            description.appendText("is activity")
        }

        public override fun matchesSafely(root: Root): Boolean {
            val type: Int = root.windowLayoutParams.get().type
            if (type == WindowManager.LayoutParams.TYPE_BASE_APPLICATION) {
                val windowToken: IBinder = root.decorView.windowToken
                val appToken: IBinder = root.decorView.applicationWindowToken
                if (windowToken === appToken) {
                    //means this window isn't contained by any other windows.
                    return true
                }
            }
            return false
        }
    }