有什么办法可以让espresso ViewAssert用于正则表达式?

时间:2019-05-27 16:04:59

标签: android android-espresso ui-automation

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

onView(withId(R.id.element_id)).check(matches(withRegEx("\\+d")));

1 个答案:

答案 0 :(得分:1)

我试图寻找一种在意式浓缩咖啡中已经存在的匹配器,但也找不到。一个建议是创建自己的。这是使用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
}

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

您可以使用此小工厂功能:

 private fun withPattern(regex: String): Matcher<in View>? = RegexMatcher(regex)

然后您可以像使用它一样

onView(withId(R.id.element_id)).check(matches(withPattern("\\+d")))

希望这会有所帮助