有没有办法让 espresso ViewAssert 用于正则表达式?

Roy*_*nos 2 android ui-automation android-espresso

我想知道是否有任何方法可以为正则表达式生成 espresso ViewAssert,例如:

onView(withId(R.id.element_id)).check(matches(withRegEx("\\+d")));
Run Code Online (Sandbox Code Playgroud)

Fre*_*red 5

我试图寻找浓缩咖啡中已经存在的匹配器,但也没有找到。一个建议是创建您自己的。这是一个使用 kotlin 的示例:

class RegexMatcher(private val regex: String) : BoundedMatcher<View, TextView>(TextView::class.java) {
    private val pattern = Pattern.compile(regex)

    override fun describeTo(description: Description?) {
        description?.appendText("Checking the matcher on received view: with pattern=$regex")
    }

    override fun matchesSafely(item: TextView?) =
        item?.text?.let {
            pattern.matcher(it).matches()
        } ?: false
}
Run Code Online (Sandbox Code Playgroud)

这定义了一个匹配器,它将检查TextViews 的文本是否与特定的正则表达式模式匹配。

你可以拥有这个小工厂功能:

 private fun withPattern(regex: String): Matcher<in View>? = RegexMatcher(regex)
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

onView(withId(R.id.element_id)).check(matches(withPattern("\\+d")))
Run Code Online (Sandbox Code Playgroud)

希望这个对你有帮助