首页 > 解决方案 > Kotlin 中的 Espresso 正则表达式匹配器

问题描述

我想为 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但失败的东西。谁能帮我?

标签: androidregexkotlinandroid-espressouitest

解决方案


您的正则表达式模式不包括字符串的前面部分。您需要包含一些内容来捕获该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


推荐阅读