【问题标题】:Espresso regex matcher in Kotlin [duplicate]Kotlin 中的 Espresso 正则表达式匹配器 [重复]
【发布时间】:2021-07-05 01:32:11
【问题描述】:

我想为 Espresso 创建一个自定义正则表达式匹配器,以便我可以检查屏幕上的文本是否包含格式为 HH:mm 的时间,例如 23:3404:23

我有一个正则表达式匹配器类:

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
}

还有一个功能:

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

屏幕上的文字说:Sometext 08:23时间当然是动态的

我的 UI 检查是这样写的:

onView(withText(startsWith("Sometext"))).check(matches(withPattern("/(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/")))

但测试总是失败,我不知道为什么。即使我只是使用像/^Sometext 这样简单的东西,它也会失败。谁能帮帮我?

【问题讨论】:

    标签: android regex kotlin android-espresso uitest


    【解决方案1】:

    您的正则表达式模式不包括字符串的前面部分。您需要包含一些内容来捕获该Sometext 部分。你用什么来捕捉开始部分取决于你期望它是什么。如果它只是非数字,您可以使用.*(匹配任何字符,0 到无穷次)或\D*(匹配任何非数字字符,0 到无穷次)。如果你知道你有规范,比如说,你总是有一个类似于The time is: {time} 的字符串,你可以简单地添加指定的字符串。

    /.*(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ /\D*(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ /The time is: (0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

    我建议您使用正则表达式工具来让您的正则表达式恰到好处。我的首选是Regex101

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2012-10-31
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多