android - Kotlin 中的 Espresso 正则表达式匹配器
问题描述
我想为 Espresso 创建一个自定义正则表达式匹配器,以便我可以检查屏幕上的文本是否包含时间格式HH:mm
,例如23:34
或04: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
但失败的东西。谁能帮我?
解决方案
您的正则表达式模式不包括字符串的前面部分。您需要包含一些内容来捕获该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。
推荐阅读
- idris - 使用递归类型定义类型 -> 类型函数
- ios - 闭包如何在本地范围内捕获原始值
- json - 错误无法识别的字符转义(CTRL-CHAR,代码 28)放心
- mysql - 在 SQL 中查找间接连接的表
- javafx - 从不同的包中定位 fxml 文件
- java - Java Mail Api 抛出 MessagingException:异常读取响应
- javascript - 函数返回值未定义
- wordpress - 在 Gutenberg 块的后端视图中使用附件 ID 属性获取附件 url
- android - 哪一种是在android中以长格式获取时间戳的最佳方法?
- python - Python Flask: returns the same dictionary in every request