【问题标题】:Is there any way to have espresso ViewAssert for regular expressions?有什么方法可以让正则表达式使用 espresso ViewAssert?
【发布时间】:2021-05-12 19:36:02
【问题描述】:

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

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

【问题讨论】:

  • 你想达到什么目的?匹配视图上的文本?

标签: android android-espresso ui-automation


【解决方案1】:

我试图寻找 espresso 中已经存在的匹配器,但也没有找到。一个建议是创建自己的。这是一个使用 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
}

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

你可以拥有这个小工厂函数:

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

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

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

希望对你有所帮助

【讨论】:

  • 谢谢,我试试。 :)
  • 非常感谢您的分享。以上对我来说非常有效。
猜你喜欢
  • 2016-08-18
  • 2021-12-27
  • 1970-01-01
  • 2013-10-27
  • 2012-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多